<template>
  <div class="education-dashboard">
    <!-- 背景渐变层 -->
    <div class="background-gradient"></div>

    <NavBar @toggle-sidebar="toggleSidebar" />

    <!-- 左侧边栏 -->
    <aside class="sidebar">
      <!-- 系统标题 -->
      <div class="sidebar-header">
        <div class="system-logo">
          <el-icon><User /></el-icon>
        </div>
        <div class="system-info">
          <h3 class="system-title">教育系统</h3>
          <p class="system-subtitle">管理平台</p>
        </div>
      </div>

      <!-- 导航菜单 -->
      <nav class="sidebar-nav">
        <div
            v-for="(item, index) in menuItems"
            :key="index"
            class="nav-item"
            :class="{ active: item.active }"
            @click="setActiveMenu(index)"
        >
          <div class="nav-icon">
            <svg v-if="item.iconClass === 'icon-home'" class="icon-home" width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M1.5 6.5L7.5 1.5L13.5 6.5V12.5C13.5 13.3284 12.8284 14 12 14H3C2.17157 14 1.5 13.3284 1.5 12.5V6.5Z" stroke="black" stroke-width="2"/>
              <path d="M5.5 14V8H9.5V14" stroke="black" stroke-width="2"/>
            </svg>
            <svg v-else-if="item.iconClass === 'icon-students'" class="icon-students" width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg">
              <circle cx="3.75" cy="3.75" r="2.25" stroke="black" stroke-width="2"/>
              <path d="M1.5 13.5V11.25C1.5 9.7575 2.2575 9 3.75 9C5.2425 9 6 9.7575 6 11.25V13.5" stroke="black" stroke-width="2"/>
              <circle cx="11.25" cy="3.75" r="2.25" stroke="black" stroke-width="2"/>
              <path d="M9 13.5V11.25C9 9.7575 9.7575 9 11.25 9C12.7425 9 13.5 9.7575 13.5 11.25V13.5" stroke="black" stroke-width="2"/>
            </svg>
            <svg v-else-if="item.iconClass === 'icon-courses'" class="icon-courses" width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M1.5 1.5H13.5V10.5H1.5V1.5Z" stroke="black" stroke-width="2"/>
              <path d="M4.5 13.5H10.5" stroke="black" stroke-width="2" stroke-linecap="round"/>
              <path d="M3 10.5L4.5 13.5" stroke="black" stroke-width="2" stroke-linecap="round"/>
              <path d="M12 10.5L10.5 13.5" stroke="black" stroke-width="2" stroke-linecap="round"/>
            </svg>
            <svg v-else-if="item.iconClass === 'icon-exam'" class="icon-exam" width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M2.5 2.5H12.5V12.5H2.5V2.5Z" stroke="black" stroke-width="2"/>
              <path d="M4.5 5.5H10.5" stroke="black" stroke-width="2" stroke-linecap="round"/>
              <path d="M4.5 7.5H10.5" stroke="black" stroke-width="2" stroke-linecap="round"/>
              <path d="M4.5 9.5H8.5" stroke="black" stroke-width="2" stroke-linecap="round"/>
            </svg>
          </div>
          <span class="nav-text">{{ item.name }}</span>
        </div>
      </nav>

      <!-- 底部帮助区域 -->

    </aside>

    <!-- 主内容区域 -->
    <main class="main-content">
      <!-- 主页面内容 -->
      <div v-if="currentPage === 'home'">
        <!-- 欢迎区域 -->
        <div class="welcome-section">
          <div class="welcome-header">
            <div class="welcome-text">
              <h1 class="welcome-title">
                欢迎回来，{{ userInfo.loading ? '老师' : userInfo.username }}！
              </h1>
              <p class="welcome-subtitle">今天又是充满活力的一天，让我们一起管理好班级事务吧</p>
            </div>
            <div class="welcome-time">
              <div class="current-date">{{ getCurrentDate() }}</div>
              <div class="current-time">{{ getCurrentTime() }}</div>
            </div>
          </div>
        </div>

        <!-- 快速统计 -->
        <div class="quick-stats">
          <div class="stat-card">
            <div class="stat-icon stat-icon-primary">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M17 21V19C17 17.9391 16.5786 16.9217 15.8284 16.1716C15.0783 15.4214 14.0609 15 13 15H5C3.93913 15 2.92172 15.4214 2.17157 16.1716C1.42143 16.9217 1 17.9391 1 19V21" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <circle cx="9" cy="7" r="4" stroke="currentColor" stroke-width="2"/>
                <path d="M23 21V19C23 18.1645 22.7246 17.3541 22.2219 16.6988C21.7193 16.0434 21.0197 15.5824 20.22 15.3927" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M16 3.13C16.8003 3.31945 17.5 3.78097 18.0027 4.43648C18.5054 5.09198 18.7808 5.90235 18.7808 6.73775C18.7808 7.57314 18.5054 8.38351 18.0027 9.03902C17.5 9.69452 16.8003 10.156 16 10.3455" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ getTotalStudentsAll() }}</div>
              <div class="stat-label">总学生数</div>
            </div>
          </div>

          <div class="stat-card">
            <div class="stat-icon stat-icon-success">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M6 2L3 6V20C3 20.5304 3.21071 21.0391 3.58579 21.4142C3.96086 21.7893 4.46957 22 5 22H19C19.5304 22 20.0391 21.7893 20.4142 21.4142C20.7893 21.0391 21 20.5304 21 20V6L18 2H6Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M3 6H21" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M16 10C16 11.0609 15.5786 12.0783 14.8284 12.8284C14.0783 13.5786 13.0609 14 12 14C10.9391 14 9.92172 13.5786 9.17157 12.8284C8.42143 12.0783 8 11.0609 8 10" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ classes.length }}</div>
              <div class="stat-label">管理班级</div>
            </div>
          </div>

          <div class="stat-card">
            <div class="stat-icon stat-icon-info">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M14 2H6C5.46957 2 4.96086 2.21071 4.58579 2.58579C4.21071 2.96086 4 3.46957 4 4V20C4 20.5304 4.21071 21.0391 4.58579 21.4142C4.96086 21.7893 5.46957 22 6 22H18C18.5304 22 19.0391 21.7893 19.4142 21.4142C19.7893 21.0391 20 20.5304 20 20V8L14 2Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M14 2V8H20" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M16 13H8" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M16 17H8" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M10 9H9H8" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ publishedExams.length }}</div>
              <div class="stat-label">创建的考试</div>
              <div class="stat-detail">
                <span class="stat-sub">草稿: {{ getDraftExamsCount() }}</span>
                <span class="stat-sub">已发布: {{ getPublishedExamsCount() }}</span>
              </div>
            </div>
          </div>

          <div class="stat-card">
            <div class="stat-icon stat-icon-warning">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
                <path d="M12 6V12L16 14" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ getRecentActivitiesCount() }}</div>
              <div class="stat-label">今日活动</div>
            </div>
          </div>
        </div>

        <!-- 主要内容区域 -->
        <div class="home-main-content">
          <!-- 最近活动 -->
          <div class="activity-section">
            <div class="section-header">
              <h2 class="section-title">最近活动</h2>
              <button class="btn btn-outline btn-sm" @click="refreshActivities()">
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M8 1V5L12 1H8ZM8 15C4.13401 15 1 11.866 1 8C1 4.13401 4.13401 1 8 1" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
                刷新
              </button>
            </div>

            <div class="activity-timeline">
              <div
                  v-for="activity in recentActivities.slice(0, 6)"
                  :key="activity.id"
                  class="activity-item"
                  :class="'activity-' + activity.color"
              >
                <div class="activity-icon">
                  <svg v-if="activity.icon === 'user-plus'" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M8 8C10.2091 8 12 6.20914 12 4C12 1.79086 10.2091 0 8 0C5.79086 0 4 1.79086 4 4C4 6.20914 5.79086 8 8 8Z" fill="currentColor"/>
                    <path d="M8 10C5.79086 10 4 11.7909 4 14V16H12V14C12 11.7909 10.2091 10 8 10Z" fill="currentColor"/>
                    <path d="M13 7H15V9H13V7Z" fill="currentColor"/>
                    <path d="M14 6V10H14" stroke="currentColor" stroke-width="1"/>
                  </svg>
                  <svg v-else-if="activity.icon === 'file-text'" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M2.5 2.5H10.5L13.5 5.5V13.5H2.5V2.5Z" stroke="currentColor" stroke-width="1.5" fill="none"/>
                    <path d="M10.5 2.5V5.5H13.5" stroke="currentColor" stroke-width="1.5" fill="none"/>
                    <path d="M4.5 7.5H11.5" stroke="currentColor" stroke-width="1.5"/>
                    <path d="M4.5 9.5H11.5" stroke="currentColor" stroke-width="1.5"/>
                    <path d="M4.5 11.5H8.5" stroke="currentColor" stroke-width="1.5"/>
                  </svg>
                  <svg v-else-if="activity.icon === 'users'" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <circle cx="5" cy="4" r="2.5" stroke="currentColor" stroke-width="1.5"/>
                    <path d="M1 14V12.5C1 10.5 2.5 9 4.5 9H5.5C7.5 9 9 10.5 9 12.5V14" stroke="currentColor" stroke-width="1.5"/>
                    <circle cx="11" cy="5" r="2" stroke="currentColor" stroke-width="1.5"/>
                    <path d="M9.5 15V13.75C9.5 12.5 10.5 11.5 11.75 11.5H11.25C12.5 11.5 13.5 12.5 13.5 13.75V15" stroke="currentColor" stroke-width="1.5"/>
                  </svg>
                  <svg v-else-if="activity.icon === 'book'" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M2 2H7C7.53043 2 8.03914 2.21071 8.41421 2.58579C8.78929 2.96086 9 3.46957 9 4V14C9 13.4696 8.78929 12.9609 8.41421 12.5858C8.03914 12.2107 7.53043 12 7 12H2V2Z" stroke="currentColor" stroke-width="1.5"/>
                    <path d="M14 2H9C8.46957 2 7.96086 2.21071 7.58579 2.58579C7.21071 2.96086 7 3.46957 7 4V14C7 13.4696 7.21071 12.9609 7.58579 12.5858C7.96086 12.2107 8.46957 12 9 12H14V2Z" stroke="currentColor" stroke-width="1.5"/>
                  </svg>
                  <svg v-else-if="activity.icon === 'edit'" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M7 2.5L13.5 9L7 15.5L0.5 9L7 2.5Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                  </svg>
                </div>
                <div class="activity-content">
                  <div class="activity-title">{{ activity.title }}</div>
                  <div class="activity-description">{{ activity.description }}</div>
                  <div class="activity-time">{{ activity.time }}</div>
                </div>
              </div>
            </div>

            <div class="activity-footer" v-if="recentActivities.length > 6">
              <button class="btn btn-secondary btn-sm">
                查看更多活动 ({{ recentActivities.length - 6 }}条)
              </button>
            </div>
          </div>

          <!-- 快捷操作 -->
          <div class="quick-actions">
            <div class="section-header">
              <h2 class="section-title">快捷操作</h2>
            </div>

            <div class="action-grid">
              <div class="action-card" @click="showCreateModal = true">
                <div class="action-icon action-icon-primary">
                  <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M10 1V19M1 10H19" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                  </svg>
                </div>
                <div class="action-content">
                  <div class="action-title">创建班级</div>
                  <div class="action-desc">快速创建新的班级</div>
                </div>
              </div>

              <div class="action-card" @click="showCreateExamModal = true">
                <div class="action-icon action-icon-info">
                  <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M3 3H17V15H3V3Z" stroke="currentColor" stroke-width="2"/>
                    <path d="M6 6H14" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                    <path d="M6 9H14" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                    <path d="M6 12H11" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                  </svg>
                </div>
                <div class="action-content">
                  <div class="action-title">创建考试</div>
                  <div class="action-desc">创建新的考试模板</div>
                </div>
              </div>

              <div class="action-card" @click="showAddStudentModal = true">
                <div class="action-icon action-icon-success">
                  <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <circle cx="7" cy="7" r="3" stroke="currentColor" stroke-width="2"/>
                    <path d="M2 18V16C2 14 4 12 7 12C10 12 12 14 12 16V18" stroke="currentColor" stroke-width="2"/>
                    <path d="M15 5V11M12 8H18" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                  </svg>
                </div>
                <div class="action-content">
                  <div class="action-title">添加学生至班级</div>
                  <div class="action-desc">通过ID将学生加入班级</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 班级管理页面内容 -->
      <div v-if="currentPage === 'classes'">
        <!-- 页面标题 -->
        <div class="page-header">
          <h1 class="page-title">班级管理</h1>
          <p class="page-subtitle">管理和查看所有班级信息</p>
        </div>

        <!-- 合并后的操作栏和统计信息 -->
        <div class="combined-actions-stats">
          <!-- 左侧操作按钮 -->
          <div class="actions-left">
            <button class="btn btn-primary" @click="showCreateModal = true">
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M8 1V15M1 8H15" stroke="white" stroke-width="2" stroke-linecap="round"/>
              </svg>
              创建班级
            </button>
            <button class="btn btn-success" @click="showAddStudentModal = true">
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                <circle cx="6" cy="6" r="2.5" stroke="white" stroke-width="2"/>
                <path d="M2 14V12.5C2 11 3 10 4.5 10H7.5C9 10 10 11 10 12.5V14" stroke="white" stroke-width="2"/>
                <path d="M12 4V10M9 7H15" stroke="white" stroke-width="2" stroke-linecap="round"/>
              </svg>
              添加学生
            </button>
            <button class="btn btn-secondary" @click="loadClasses()" :disabled="loading">
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M8 1V5L12 1H8ZM8 15C4.13401 15 1 11.866 1 8C1 4.13401 4.13401 1 8 1" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
              刷新数据
            </button>
          </div>

          <!-- 中间统计信息 -->
          <div class="inline-stats">
            <div class="stat-item">
              <span class="stat-number">{{ filteredClasses.length }}</span>
              <span class="stat-text">总班级数</span>
            </div>
            <div class="stat-divider"></div>
            <div class="stat-item">
              <span class="stat-number">{{ getTotalStudents() }}</span>
              <span class="stat-text">总学生数</span>
            </div>
          </div>

          <!-- 右侧搜索框 -->
          <div class="search-box">
            <input
                type="text"
                placeholder="搜索班级..."
                v-model="searchKeyword"
                class="search-input"
            >
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" class="search-icon">
              <circle cx="7" cy="7" r="6" stroke="#64748B" stroke-width="2"/>
              <path d="M13 13L15 15" stroke="#64748B" stroke-width="2" stroke-linecap="round"/>
            </svg>
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <div class="loading-spinner"></div>
          <p>加载中...</p>
        </div>

        <!-- 班级列表 -->
        <div v-else class="class-list">
          <div v-if="filteredClasses.length === 0" class="empty-state">
            <div class="empty-icon">
              <svg width="64" height="64" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
                <circle cx="32" cy="32" r="30" stroke="#E2E8F0" stroke-width="4"/>
                <path d="M20 32H44M32 20V44" stroke="#E2E8F0" stroke-width="4" stroke-linecap="round"/>
              </svg>
            </div>
            <p class="empty-text">{{ searchKeyword ? '没有找到匹配的班级' : '暂无班级数据' }}</p>
            <button v-if="!searchKeyword" class="btn btn-primary" @click="showCreateModal = true">创建第一个班级</button>
          </div>

          <div v-else>
            <div class="class-grid">
              <div
                  v-for="classItem in paginatedClasses"
                  :key="classItem.class_id"
                  class="class-card"
              >
                <div class="class-header">
                  <div class="class-info">
                    <h3 class="class-name">{{ classItem.name }}</h3>
                  </div>
                </div>

                <div class="class-details">
                  <div class="detail-item">
                    <span class="detail-label">班级描述:</span>
                    <span class="detail-value">{{ classItem.description || '无描述' }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="detail-label">学生数量:</span>
                    <span class="detail-value student-count">{{ classItem.studentCount || 0 }}人</span>
                  </div>
                  <div class="detail-item">
                    <span class="detail-label">班级ID:</span>
                    <span class="detail-value">{{ classItem.class_id }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="detail-label">创建时间:</span>
                    <span class="detail-value">{{ formatDate(classItem.createdAt) }}</span>
                  </div>
                </div>

                <div class="class-actions-buttons">
                  <button class="btn btn-outline btn-action" @click="editClass(classItem)">
                    <el-icon><Edit /></el-icon>
                    编辑
                  </button>
                  <button class="btn btn-info btn-action" @click="viewStudents(classItem)">
                    <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <circle cx="4.5" cy="3" r="1.5" stroke="currentColor" stroke-width="1.2"/>
                      <path d="M2 10V9C2 8.17157 2.67157 7.5 3.5 7.5H5.5C6.32843 7.5 7 8.17157 7 9V10" stroke="currentColor" stroke-width="1.2"/>
                      <circle cx="8.5" cy="4.5" r="1.25" stroke="currentColor" stroke-width="1.2"/>
                      <path d="M7 11V10.25C7 9.7 7.4 9.25 7.75 9.25H9.25C9.6 9.25 10 9.7 10 10.25V11" stroke="currentColor" stroke-width="1.2"/>
                    </svg>
                    学生
                  </button>
                  <button class="btn btn-secondary btn-action" @click="getInviteCode(classItem.name)">
                    <el-icon><Share /></el-icon>
                    邀请
                  </button>
                  <button class="btn btn-danger btn-action" @click="confirmDeleteClass(classItem)">
                    <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M1.5 3H10.5M4.5 3V2C4.5 1.5 4.8 1.2 5.2 1.2H6.8C7.2 1.2 7.5 1.5 7.5 2V3M9.5 3V10C9.5 10.5 9.2 10.8 8.8 10.8H3.2C2.8 10.8 2.5 10.5 2.5 10V3" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                    删除
                  </button>
                </div>
              </div>
            </div>

            <!-- 分页组件 -->
            <div class="pagination-container">
              <div class="pagination-info">
                <span class="pagination-text">
                  显示第 {{ startIndex }} - {{ endIndex }} 条，共 {{ filteredClasses.length }} 条记录
                </span>
              </div>

              <div class="pagination-controls">
                <!-- 上一页按钮 -->
                <button
                    class="pagination-btn pagination-btn-prev"
                    :disabled="pagination.currentPage === 1"
                    @click="previousPage"
                >
                  <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M10 12L6 8L10 4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                  </svg>
                  上一页
                </button>

                <!-- 页码按钮 -->
                <div class="pagination-pages">
                  <!-- 第一页 -->
                  <button
                      v-if="pagination.currentPage > 3"
                      class="pagination-btn pagination-btn-page"
                      @click="goToPage(1)"
                  >
                    1
                  </button>

                  <!-- 省略号 -->
                  <span v-if="pagination.currentPage > 4" class="pagination-ellipsis">...</span>

                  <!-- 当前页附近的页码 -->
                  <button
                      v-for="page in visiblePages"
                      :key="page"
                      class="pagination-btn pagination-btn-page"
                      :class="{ active: page === pagination.currentPage }"
                      @click="goToPage(page)"
                  >
                    {{ page }}
                  </button>

                  <!-- 省略号 -->
                  <span v-if="pagination.currentPage < pagination.totalPages - 3" class="pagination-ellipsis">...</span>

                  <!-- 最后一页 -->
                  <button
                      v-if="pagination.currentPage < pagination.totalPages - 2"
                      class="pagination-btn pagination-btn-page"
                      @click="goToPage(pagination.totalPages)"
                  >
                    {{ pagination.totalPages }}
                  </button>
                </div>

                <!-- 下一页按钮 -->
                <button
                    class="pagination-btn pagination-btn-next"
                    :disabled="pagination.currentPage === pagination.totalPages"
                    @click="nextPage"
                >
                  下一页
                  <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M6 4L10 8L6 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                  </svg>
                </button>
              </div>

              <!-- 分页设置 -->
              <div class="pagination-settings">
                <label class="pagination-label">每页显示：</label>
                <select
                    v-model.number="pagination.pageSize"
                    @change="onPageSizeChange"
                    class="pagination-select"
                >
                  <option :value="1">1条</option>
                  <option :value="3">3条</option>
                  <option :value="6">6条</option>
                  <option :value="12">12条</option>
                  <option :value="24">24条</option>
                  <option :value="50">50条</option>
                </select>
              </div>

              <!-- 快速跳转 -->
              <div class="pagination-jumper">
                <span class="pagination-text">跳转到</span>
                <input
                    type="number"
                    v-model.number="jumpPage"
                    @keyup.enter="jumpToPage"
                    :min="1"
                    :max="pagination.totalPages"
                    class="pagination-input"
                >
                <span class="pagination-text">页</span>
                <button
                    class="btn btn-secondary btn-sm"
                    @click="jumpToPage"
                    :disabled="!isValidJumpPage"
                >
                  确定
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 考试中心页面内容 -->
      <div v-if="currentPage === 'exam'">
        <!-- 页面标题 -->
        <div class="page-header">
          <h1 class="page-title">考试中心</h1>
          <p class="page-subtitle">创建考试，管理已创建的考试内容</p>
        </div>

        <!-- 重新设计的操作栏和统计信息 -->
        <div class="exam-header-layout">
          <!-- 左侧：操作按钮 -->
          <div class="exam-actions-left">
            <button class="btn btn-primary" @click="showCreateExamModal = true">
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M8 1V15M1 8H15" stroke="white" stroke-width="2" stroke-linecap="round"/>
              </svg>
              创建考试
            </button>
            <button class="btn btn-secondary" @click="loadPublishedExams()">
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M8 1V5L12 1H8ZM8 15C4.13401 15 1 11.866 1 8C1 4.13401 4.13401 1 8 1" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
              刷新数据
            </button>
          </div>

          <!-- 中间：搜索框 -->
          <div class="exam-search-center">
            <div class="search-box">
              <input
                  type="text"
                  placeholder="搜索考试名称..."
                  v-model="examSearchKeyword"
                  class="search-input"
              >
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" class="search-icon">
                <circle cx="7" cy="7" r="6" stroke="#64748B" stroke-width="2"/>
                <path d="M13 13L15 15" stroke="#64748B" stroke-width="2" stroke-linecap="round"/>
              </svg>
            </div>
          </div>

          <!-- 右侧：统计信息 -->
          <div class="exam-stats-right">
            <div class="exam-stats-item">
              <span class="exam-stat-number">{{ getDraftExamsCount() }}</span>
              <span class="exam-stat-text">草稿考试</span>
            </div>
            <div class="exam-stat-divider"></div>
            <div class="exam-stats-item">
              <span class="exam-stat-number">{{ getPublishedExamsCount() }}</span>
              <span class="exam-stat-text">已发布考试</span>
            </div>
            <div class="exam-stat-divider"></div>
            <div class="exam-stats-item">
              <span class="exam-stat-number">{{ filteredExams.length }}</span>
              <span class="exam-stat-text">总考试数</span>
            </div>
          </div>
        </div>

        <!-- 已创建考试列表 -->
        <div class="published-content">
          <div class="content-section">
            <h3 class="section-title">已创建考试</h3>
            <div v-if="filteredExams.length === 0" class="empty-state">
              <div class="empty-icon">
                <svg width="64" height="64" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <circle cx="32" cy="32" r="30" stroke="#E2E8F0" stroke-width="4"/>
                  <path d="M20 32H44M32 20V44" stroke="#E2E8F0" stroke-width="4" stroke-linecap="round"/>
                </svg>
              </div>
              <p class="empty-text">{{ examSearchKeyword ? '没有找到匹配的考试' : '暂无已创建的考试' }}</p>
            </div>
            <div v-else>
              <div class="published-grid">
                <div v-for="exam in paginatedFilteredExams" :key="exam.id" class="published-card" :class="getExamCardClass(exam.status)">
                  <div class="card-header">
                    <div class="card-info">
                      <h4 class="card-title">{{ exam.title }}</h4>
                      <div class="card-badges">
                        <span class="card-type exam-type">考试</span>
                        <span class="status-badge" :class="getStatusBadgeClass(exam.status)">
                          {{ getStatusText(exam.status) }}
                        </span>
                      </div>
                    </div>
                  </div>
                  <div class="card-details">
                    <div class="detail-item">
                      <span class="detail-label">考试描述:</span>
                      <span class="detail-value">{{ exam.description }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">开始时间:</span>
                      <span class="detail-value">{{ exam.examTime }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">结束时间:</span>
                      <span class="detail-value">{{ exam.endTime }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">考试时长:</span>
                      <span class="detail-value">{{ exam.duration }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">发布班级:</span>
                      <span class="detail-value">{{ exam.publishedClasses.length > 0 ? exam.publishedClasses.join(', ') : '未指定' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">创建时间:</span>
                      <span class="detail-value">{{ exam.publishTime }}</span>
                    </div>
                  </div>
                  <div class="card-actions">
                    <!-- 发布考试按钮 - 根据状态决定是否可点击 -->
                    <button
                        class="btn btn-sm"
                        :class="exam.status === 'DRAFT' ? 'btn-primary' : 'btn-secondary'"
                        :disabled="exam.status === 'PUBLISHED'"
                        @click="exam.status === 'DRAFT' ? publishExamFromCard(exam) : null"
                    >
                      <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M8 1V11M1 6H11" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
                      </svg>
                      {{ exam.status === 'DRAFT' ? '发布考试' : '已发布' }}
                    </button>

                    <!-- 共同操作 -->
                    <button class="btn btn-info btn-sm" @click="gotoQuestions(exam.id)">
                      <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M2 2H7C7.53043 2 8.03914 2.21071 8.41421 2.58579C8.78929 2.96086 9 3.46957 9 4V10C9 9.46957 8.78929 8.96086 8.41421 8.58579C8.03914 8.21071 7.53043 8 7 8H2V2Z" stroke="currentColor" stroke-width="1.2"/>
                        <path d="M10 2H9C8.46957 2 7.96086 2.21071 7.58579 2.58579C7.21071 2.96086 7 3.46957 7 4V10C7 9.46957 7.21071 8.96086 7.58579 8.58579C7.96086 8.21071 8.46957 8 9 8H10V2Z" stroke="currentColor" stroke-width="1.2"/>
                      </svg>
                      选择习题
                    </button>
                    <button class="btn btn-danger btn-sm" @click="confirmDeletePublish(exam)">
                      <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M1.75 3.5H10.25M4.25 3.5V2.33333C4.25 1.8731 4.6231 1.5 5.08333 1.5H6.91667C7.3769 1.5 7.75 1.8731 7.75 2.33333V3.5M9.0833 3.5V9.66667C9.0833 10.1269 8.7102 10.5 8.25 10.5H3.75C3.2898 10.5 2.91667 10.1269 2.91667 9.66667V3.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
                      </svg>
                      删除
                    </button>
                  </div>
                </div>
              </div>

              <!-- 考试分页组件 -->
              <div class="pagination-container">
                <div class="pagination-info">
                  <span class="pagination-text">
                    显示第 {{ startIndexFilteredExams }} - {{ endIndexFilteredExams }} 条，共 {{ filteredExams.length }} 条记录
                  </span>
                </div>

                <div class="pagination-controls">
                  <button
                      class="pagination-btn pagination-btn-prev"
                      :disabled="paginationExams.currentPage === 1"
                      @click="previousPageExams"
                  >
                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M10 12L6 8L10 4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                    上一页
                  </button>

                  <div class="pagination-pages">
                    <button
                        v-if="paginationExams.currentPage > 3"
                        class="pagination-btn pagination-btn-page"
                        @click="goToPageExams(1)"
                    >
                      1
                    </button>

                    <span v-if="paginationExams.currentPage > 4" class="pagination-ellipsis">...</span>

                    <button
                        v-for="page in visiblePagesExams"
                        :key="page"
                        class="pagination-btn pagination-btn-page"
                        :class="{ active: page === paginationExams.currentPage }"
                        @click="goToPageExams(page)"
                    >
                      {{ page }}
                    </button>

                    <span v-if="paginationExams.currentPage < paginationExams.totalPages - 3" class="pagination-ellipsis">...</span>

                    <button
                        v-if="paginationExams.currentPage < paginationExams.totalPages - 2"
                        class="pagination-btn pagination-btn-page"
                        @click="goToPageExams(paginationExams.totalPages)"
                    >
                      {{ paginationExams.totalPages }}
                    </button>
                  </div>

                  <button
                      class="pagination-btn pagination-btn-next"
                      :disabled="paginationExams.currentPage === paginationExams.totalPages"
                      @click="nextPageExams"
                  >
                    下一页
                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M6 4L10 8L6 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                  </button>
                </div>

                <div class="pagination-settings">
                  <label class="pagination-label">每页显示：</label>
                  <select
                      v-model.number="paginationExams.pageSize"
                      @change="onPageSizeChangeExams"
                      class="pagination-select"
                  >
                    <option :value="1">1条</option>
                    <option :value="3">3条</option>
                    <option :value="6">6条</option>
                    <option :value="12">12条</option>
                    <option :value="24">24条</option>
                    <option :value="50">50条</option>
                  </select>
                </div>

                <div class="pagination-jumper">
                  <span class="pagination-text">跳转到</span>
                  <input
                      type="number"
                      v-model.number="jumpPageExams"
                      @keyup.enter="jumpToPageExams"
                      :min="1"
                      :max="paginationExams.totalPages"
                      class="pagination-input"
                  >
                  <span class="pagination-text">页</span>
                  <button
                      class="btn btn-secondary btn-sm"
                      @click="jumpToPageExams"
                      :disabled="!isValidJumpPageExams"
                  >
                    确定
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 模态框部分，移动到main-content末尾，不嵌套在v-if中 -->
      <!-- 创建/编辑班级模态框 -->
      <div v-if="showCreateModal || showEditModal" class="modal-overlay" @click="closeModals">
        <div class="modal" @click.stop>
          <div class="modal-header">
            <h3 class="modal-title">{{ showCreateModal ? '创建班级' : '编辑班级' }}</h3>
            <button class="modal-close" @click="closeModals">
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M15 5L5 15M5 5L15 15" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
              </svg>
            </button>
          </div>

          <form @submit.prevent="showCreateModal ? createClass() : updateClass()" class="modal-form">
            <div class="form-group">
              <label class="form-label">班级名称 *</label>
              <input
                  type="text"
                  v-model="classForm.name"
                  class="form-input"
                  placeholder="请输入班级名称"
                  required
              >
            </div>

            <div class="form-group">
              <label class="form-label">班级描述</label>
              <textarea
                  v-model="classForm.description"
                  class="form-textarea"
                  placeholder="请输入班级描述（可选）"
                  rows="3"
              ></textarea>
            </div>

            <div class="modal-actions">
              <button type="button" class="btn btn-secondary" @click="closeModals">取消</button>
              <button type="submit" class="btn btn-primary">
                {{ showCreateModal ? '创建' : '更新' }}
              </button>
            </div>
          </form>
        </div>
      </div>

      <!-- 删除确认模态框 -->
      <div v-if="showDeleteModal" class="modal-overlay" @click="showDeleteModal = false">
        <div class="modal modal-small" @click.stop>
          <div class="modal-header">
            <h3 class="modal-title">确认删除</h3>
          </div>
          <div class="modal-body">
            <p>您确定要删除班级 "{{ deleteTarget && deleteTarget.name }}" 吗？此操作无法撤销。</p>
          </div>
          <div class="modal-actions">
            <button class="btn btn-secondary" @click="showDeleteModal = false">取消</button>
            <button class="btn btn-danger" @click="deleteClass()">确认删除</button>
          </div>
        </div>
      </div>

      <!-- 邀请码显示模态框 -->
      <div v-if="showInviteModal" class="modal-overlay" @click="showInviteModal = false">
        <div class="modal modal-small" @click.stop>
          <div class="modal-header">
            <h3 class="modal-title">班级邀请码</h3>
          </div>
          <div class="modal-body">
            <p>班级 "{{ inviteCodeData.className }}" 的邀请码为：</p>
            <div class="invite-code">{{ inviteCodeData.code }}</div>
            <p class="invite-note">请将此邀请码分享给学生，学生可使用此码加入班级。</p>
          </div>
          <div class="modal-actions">
            <button class="btn btn-primary" @click="copyInviteCode()">复制邀请码</button>
            <button class="btn btn-secondary" @click="showInviteModal = false">关闭</button>
          </div>
        </div>
      </div>

      <!-- 创建考试模态框 -->
      <div v-if="showCreateExamModal" class="modal-overlay" @click="closeExamModals">
        <div class="modal modal-minimal" @click.stop>
          <div class="modal-header modal-header-minimal">
            <h3 class="modal-title modal-title-minimal">创建考试</h3>
            <button class="modal-close" @click="closeExamModals">
              <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M13.5 4.5L4.5 13.5M4.5 4.5L13.5 13.5" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
              </svg>
            </button>
          </div>

          <form @submit.prevent="createExam()" class="modal-form modal-form-minimal">
            <div class="form-group form-group-minimal">
              <label class="form-label form-label-minimal">考试标题 *</label>
              <input
                  type="text"
                  v-model="examForm.title"
                  class="form-input form-input-minimal"
                  placeholder="请输入考试标题"
                  required
              >
            </div>

            <div class="form-group form-group-minimal">
              <label class="form-label form-label-minimal">考试描述</label>
              <textarea
                  v-model="examForm.description"
                  class="form-textarea form-textarea-minimal"
                  placeholder="请输入考试描述"
                  rows="2"
              ></textarea>
            </div>

            <div class="form-row form-row-minimal">
              <div class="form-group form-group-minimal">
                <label class="form-label form-label-minimal">考试开始时间 *</label>
                <input
                    type="datetime-local"
                    v-model="examForm.examTime"
                    class="form-input form-input-minimal"
                    required
                >
              </div>
              <div class="form-group form-group-minimal">
                <label class="form-label form-label-minimal">考试时长 *</label>
                <input
                    type="text"
                    v-model="examForm.duration"
                    class="form-input form-input-minimal"
                    placeholder="120分钟"
                    required
                >
              </div>
            </div>

            <div class="form-group form-group-minimal">
              <label class="form-label form-label-minimal">考试结束时间 *</label>
              <input
                  type="datetime-local"
                  v-model="examForm.endTime"
                  class="form-input form-input-minimal"
                  required
              >
            </div>

            <div class="form-group form-group-minimal">
              <label class="form-label form-label-minimal">选择班级 *</label>
              <div class="checkbox-group checkbox-group-minimal">
                <label v-for="classItem in classes" :key="classItem.class_id" class="checkbox-item checkbox-item-minimal">
                  <input
                      type="checkbox"
                      :value="classItem.name"
                      v-model="examForm.selectedClasses"
                      class="checkbox-input"
                  >
                  <span class="checkbox-label checkbox-label-minimal">{{ classItem.name }}</span>
                </label>
              </div>
            </div>

            <div class="modal-actions modal-actions-minimal">
              <button type="button" class="btn btn-secondary btn-minimal" @click="closeExamModals">取消</button>
              <button type="submit" class="btn btn-primary btn-minimal">创建</button>
            </div>
          </form>
        </div>
      </div>

      <!-- 添加学生至班级模态框 -->
      <div v-if="showAddStudentModal" class="modal-overlay" @click="closeModals">
        <div class="modal" @click.stop>
          <div class="modal-header">
            <h3 class="modal-title">添加学生至班级</h3>
            <button class="modal-close" @click="closeModals">
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M15 5L5 15M5 5L15 15" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
              </svg>
            </button>
          </div>

          <form @submit.prevent="addStudentToClass()" class="modal-form">
            <div class="form-group">
              <label class="form-label">班级ID *</label>
              <input
                  type="number"
                  v-model="addStudentForm.classId"
                  class="form-input"
                  placeholder="请输入班级ID"
                  required
                  :disabled="addStudentForm.loading"
              >
            </div>

            <div class="form-group">
              <label class="form-label">学生ID *</label>
              <input
                  type="number"
                  v-model="addStudentForm.studentId"
                  class="form-input"
                  placeholder="请输入学生ID"
                  required
                  :disabled="addStudentForm.loading"
              >
            </div>

            <div class="modal-actions">
              <button type="button" class="btn btn-secondary" @click="closeModals" :disabled="addStudentForm.loading">取消</button>
              <button type="submit" class="btn btn-primary" :disabled="addStudentForm.loading">
                <span v-if="addStudentForm.loading">添加中...</span>
                <span v-else>确认添加</span>
              </button>
            </div>
          </form>
        </div>
      </div>

      <!-- 学生信息显示模态框 -->
      <div v-if="showStudentsModal" class="modal-overlay" @click="showStudentsModal = false">
        <div class="modal modal-large" @click.stop>
          <div class="modal-header">
            <h3 class="modal-title">班级学生信息 - {{ studentsModalData.className }}</h3>
            <button class="modal-close" @click="showStudentsModal = false">
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M15 5L5 15M5 5L15 15" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
              </svg>
            </button>
          </div>

          <div class="modal-body">
            <!-- 加载状态 -->
            <div v-if="studentsModalData.loading" class="students-loading">
              <div class="loading-spinner"></div>
              <p>正在加载学生信息...</p>
            </div>

            <!-- 学生列表 -->
            <div v-else>
              <div v-if="studentsModalData.students.length === 0" class="empty-students">
                <div class="empty-icon">
                  <svg width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <circle cx="24" cy="24" r="22" stroke="#E2E8F0" stroke-width="4"/>
                    <path d="M16 24H32M24 16V32" stroke="#E2E8F0" stroke-width="4" stroke-linecap="round"/>
                  </svg>
                </div>
                <p class="empty-text">该班级暂无学生</p>
              </div>

              <div v-else>
                <div class="students-header">
                  <span class="students-count">共 {{ studentsModalData.students.length }} 名学生</span>
                </div>

                <div class="students-grid">
                  <div v-for="student in studentsModalData.students" :key="student.id" class="student-card">
                    <div class="student-avatar">
                      <svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <circle cx="16" cy="16" r="14" stroke="#4318D1" stroke-width="2"/>
                        <circle cx="16" cy="12" r="4" stroke="#4318D1" stroke-width="2"/>
                        <path d="M8 26C8 22 11.5 19 16 19C20.5 19 24 22 24 26" stroke="#4318D1" stroke-width="2"/>
                      </svg>
                    </div>
                    <div class="student-info">
                      <div class="student-name">{{ student.username || '未知学生' }}</div>
                      <div class="student-id">学号: {{ student.id }}</div>
                      <div class="student-role">{{ student.role || 'student' }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="modal-actions">
            <button class="btn btn-secondary" @click="showStudentsModal = false">关闭</button>
          </div>
        </div>
      </div>

      <!-- 删除考试确认模态框 -->
      <div v-if="showDeletePublishModal" class="modal-overlay" @click="showDeletePublishModal = false">
        <div class="modal modal-small" @click.stop>
          <div class="modal-header">
            <h3 class="modal-title">确认删除</h3>
          </div>
          <div class="modal-body">
            <p>您确定要删除考试 "{{ deletePublishTarget && deletePublishTarget.title }}" 吗？此操作无法撤销。</p>
          </div>
          <div class="modal-actions">
            <button class="btn btn-secondary" @click="showDeletePublishModal = false">取消</button>
            <button class="btn btn-danger" @click="deletePublishedExam()">确认删除</button>
          </div>
        </div>
      </div>

    </main>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, onUnmounted, nextTick } from 'vue'
import NavBar from '@/components/NavBar.vue'
import { useRouter } from 'vue-router'
import {publishExamAPI} from "@/apis/index.js";
const router = useRouter()

// 侧边栏状态
const sidebarCollapsed = ref(false)

// 切换侧边栏
const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

// 响应式数据
const currentPage = ref('home')
const searchKeyword = ref('')
const examSearchKeyword = ref('')
const examStatusFilter = ref('all') // 新增：考试状态过滤器
const loading = ref(false)
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
const pagination = reactive({
  currentPage: 1,
  pageSize: 6,
  totalPages: 0
})
const jumpPage = ref(1)

const paginationExams = reactive({
  currentPage: 1,
  pageSize: 3,
  totalPages: 0
})
const jumpPageExams = ref(1)

// 模态框状态
const showCreateModal = ref(false)
const showEditModal = ref(false)
const showDeleteModal = ref(false)
const showInviteModal = ref(false)
const showCreateExamModal = ref(false)
const showDeletePublishModal = ref(false)
const showStudentsModal = ref(false)
const showAddStudentModal = ref(false)
const deleteTarget = ref(null)
const deletePublishTarget = ref(null)

// 邀请码数据
const inviteCodeData = reactive({
  className: '',
  code: ''
})

// 学生信息相关
const studentsModalData = reactive({
  className: '',
  classId: null,
  students: [],
  loading: false
})

// 添加学生表单
const addStudentForm = reactive({
  classId: '',
  studentId: '',
  loading: false
})

// 班级表单
const classForm = reactive({
  class_id: null,
  name: '',
  description: ''
})

// 根据班级ID获取班级名称
const getClassNameById = (classId) => {
  if (!window.Promise) {
    return {
      then: (success) => {
        if (success) success('未知班级')
      },
      catch: () => {
        // 忽略错误
      }
    }
  }

  return new Promise((resolve) => {
    if (!window.fetch || !classId || classId === 0) {
      resolve('未指定班级')
      return
    }

    // 转换classId为数字，确保正确处理
    const numericClassId = Number(classId)
    if (isNaN(numericClassId)) {
      resolve('无效班级ID')
      return
    }

    if (window.console && console.log) {
      console.log('正在获取班级名称，classId:', numericClassId)
    }

    apiCall(`http://localhost:8080/api/classes/getClassById?classId=${numericClassId}`, 'GET')
        .then(response => {
          if (window.console && console.log) {
            console.log('获取到班级详情:', response)
          }

          if (response.data && response.data.name) {
            resolve(response.data.name)
          } else {
            resolve('未知班级')
          }
        })
        .catch(error => {
          if (window.console && console.log) {
            console.error('获取班级名称失败:', error)
          }
          resolve('未知班级')
        })
  })
}

// 加载已创建的考试列表
const loadPublishedExams = () => {
  if (!window.Promise || !window.fetch) {
    return
  }

  if (window.console && console.log) {
    console.log('开始加载已创建的考试列表，teacherId:', currentTeacherId.value)
  }

  apiCall(`http://localhost:8080/api/student/exams/teacher/${currentTeacherId.value}`, 'GET')
      .then(response => {
        if (window.console && console.log) {
          console.log('获取到已创建考试列表:', response)
        }

        if (response.data && Array.isArray(response.data)) {
          // 首先将后端数据转换为基本格式
          const baseExams = response.data.map(exam => ({
            id: exam.examId || exam.id || exam.exam_id, // 支持多种ID字段名
            title: exam.title || '未命名考试',
            description: exam.description || '无描述',
            classId: exam.classId || exam.class_id, // 支持多种classId字段名
            publishedClasses: [], // 稍后填充班级名称
            publishTime: formatDate(exam.createdAt || exam.createTime || exam.created_at),
            examTime: formatDateTime(exam.startTime || exam.start_time),
            endTime: formatDateTime(exam.endTime || exam.end_time),
            duration: exam.duration ? exam.duration + '分钟' : '未设置',
            type: 'exam',
            status: exam.status || 'PUBLISHED' // 使用后端返回的状态
          }))

          if (window.console && console.log) {
            console.log('基本考试数据处理完成:', baseExams)
          }

          // 然后为每个考试获取班级名称
          let completedCount = 0
          const totalCount = baseExams.length

          if (totalCount === 0) {
            publishedExams.value = []
            setTimeout(() => {
              updatePaginationExams()
            }, 100)
            return
          }

          baseExams.forEach((exam, index) => {
            if (exam.classId && exam.classId !== 0) {
              getClassNameById(exam.classId)
                  .then(className => {
                    baseExams[index].publishedClasses = [className]
                    completedCount++

                    if (window.console && console.log) {
                      console.log(`考试 "${exam.title}" 的班级名称获取完成: ${className} (${completedCount}/${totalCount})`)
                    }

                    if (completedCount === totalCount) {
                      publishedExams.value = baseExams
                      if (window.console && console.log) {
                        console.log('所有考试的班级名称获取完成:', publishedExams.value)
                      }
                      setTimeout(() => {
                        updatePaginationExams()
                      }, 100)
                    }
                  })
                  .catch(() => {
                    baseExams[index].publishedClasses = ['未知班级']
                    completedCount++

                    if (completedCount === totalCount) {
                      publishedExams.value = baseExams
                      setTimeout(() => {
                        updatePaginationExams()
                      }, 100)
                    }
                  })
            } else {
              baseExams[index].publishedClasses = ['未指定班级']
              completedCount++

              if (completedCount === totalCount) {
                publishedExams.value = baseExams
                setTimeout(() => {
                  updatePaginationExams()
                }, 100)
              }
            }
          })
        } else {
          publishedExams.value = []
          setTimeout(() => {
            updatePaginationExams()
          }, 100)
        }
      })
      .catch(error => {
        if (window.console && console.log) {
          console.error('获取已创建考试列表失败:', error)
        }
        publishedExams.value = []
        setTimeout(() => {
          updatePaginationExams()
        }, 100)
      })
}

// 从localStorage获取用户ID，如果没有则使用默认值2006050118
const getUserIdFromStorage = () => {
  try {
    const storedId = localStorage.getItem("id")
    if (storedId && storedId.trim() !== '' && !isNaN(Number(storedId))) {
      return Number(storedId)
    }
    // 如果localStorage中没有有效的ID，使用默认值2006050118
    console.log('使用默认用户ID: 2006050118')
    return 2006050118
  } catch (error) {
    console.error('读取localStorage失败，使用默认用户ID:', error)
    return 2006050118
  }
}

const currentTeacherId = ref(getUserIdFromStorage())

// 用户信息
const userInfo = reactive({
  id: null,
  username: '',
  loading: true
})

const classes = ref([])

// 考试中心相关数据
const publishedExams = ref([])

const examForm = reactive({
  title: '',
  description: '',
  examTime: '',
  endTime: '',
  duration: '',
  selectedClasses: []
})

const menuItems = ref([
  { name: '主页面', iconClass: 'icon-home', active: true, page: 'home' },
  { name: '班级管理', iconClass: 'icon-students', active: false, page: 'classes' },
  { name: '考试中心', iconClass: 'icon-exam', active: false, page: 'exam' }
])

// 最近活动数据
const recentActivities = ref([
  {
    id: 1,
    type: 'student_join',
    title: '新学生加入班级',
    description: '学生 "李小明" 加入了 "高中1班"',
    time: '2025年7月19日 14:30',
    icon: 'user-plus',
    color: 'success'
  },
  {
    id: 2,
    type: 'exam_publish',
    title: '发布新考试',
    description: '数学期中考试已发布到 "高中1班, 高中2班"',
    time: '2025年7月19日 10:15',
    icon: 'file-text',
    color: 'info'
  },
  {
    id: 3,
    type: 'class_create',
    title: '创建新班级',
    description: '成功创建班级 "高中3班"',
    time: '2025年7月18日 16:45',
    icon: 'users',
    color: 'primary'
  },
  {
    id: 4,
    type: 'student_join',
    title: '新学生加入班级',
    description: '学生 "王小红" 加入了 "高中2班"',
    time: '2025年7月18日 14:20',
    icon: 'user-plus',
    color: 'success'
  },
  {
    id: 5,
    type: 'exam_publish',
    title: '发布新考试',
    description: '物理单元测试已发布到 "高中2班"',
    time: '2025年7月18日 09:30',
    icon: 'file-text',
    color: 'info'
  },
  {
    id: 6,
    type: 'resource_share',
    title: '分享学习资源',
    description: '上传了新的学习资料到 "高中1班"',
    time: '2025年7月17日 15:10',
    icon: 'book',
    color: 'warning'
  },
  {
    id: 7,
    type: 'student_join',
    title: '新学生加入班级',
    description: '学生 "张小刚" 加入了 "高中1班"',
    time: '2025年7月17日 11:25',
    icon: 'user-plus',
    color: 'success'
  },
  {
    id: 8,
    type: 'class_update',
    title: '更新班级信息',
    description: '修改了 "高中1班" 的班级描述',
    time: '2025年7月16日 13:40',
    icon: 'edit',
    color: 'secondary'
  }
])

// 计算属性
const filteredClasses = computed(() => {
  if (!searchKeyword.value) {
    return classes.value
  }
  return classes.value.filter(classItem => {
    return classItem.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
        (classItem.description && classItem.description.toLowerCase().includes(searchKeyword.value.toLowerCase()))
  })
})

const paginatedClasses = computed(() => {
  const pageSize = Number(pagination.pageSize)
  const currentPage = Number(pagination.currentPage)
  const start = (currentPage - 1) * pageSize
  const end = start + pageSize
  return filteredClasses.value.slice(start, end)
})

const visiblePages = computed(() => {
  const total = pagination.totalPages
  const current = pagination.currentPage
  const pages = []
  const start = Math.max(1, current - 2)
  const end = Math.min(total, current + 2)
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  return pages
})

const startIndex = computed(() => {
  const pageSize = Number(pagination.pageSize)
  const currentPage = Number(pagination.currentPage)
  return (currentPage - 1) * pageSize + 1
})

const endIndex = computed(() => {
  const pageSize = Number(pagination.pageSize)
  const currentPage = Number(pagination.currentPage)
  const end = currentPage * pageSize
  return Math.min(end, filteredClasses.value.length)
})

const isValidJumpPage = computed(() => {
  return jumpPage.value >= 1 && jumpPage.value <= pagination.totalPages && jumpPage.value !== pagination.currentPage
})

// 考试相关计算属性 - 去掉状态过滤，只保留搜索过滤
const filteredExams = computed(() => {
  let filtered = publishedExams.value

  // 只按搜索关键词过滤
  if (examSearchKeyword.value) {
    filtered = filtered.filter(exam => {
      return exam.title.toLowerCase().includes(examSearchKeyword.value.toLowerCase()) ||
          exam.description.toLowerCase().includes(examSearchKeyword.value.toLowerCase())
    })
  }

  return filtered
})

const paginatedFilteredExams = computed(() => {
  const pageSize = Number(paginationExams.pageSize)
  const currentPage = Number(paginationExams.currentPage)
  const start = (currentPage - 1) * pageSize
  const end = start + pageSize
  return filteredExams.value.slice(start, end)
})

const visiblePagesExams = computed(() => {
  const total = paginationExams.totalPages
  const current = paginationExams.currentPage
  const pages = []
  const start = Math.max(1, current - 2)
  const end = Math.min(total, current + 2)
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  return pages
})

const startIndexFilteredExams = computed(() => {
  const pageSize = Number(paginationExams.pageSize)
  const currentPage = Number(paginationExams.currentPage)
  return (currentPage - 1) * pageSize + 1
})

const endIndexFilteredExams = computed(() => {
  const pageSize = Number(paginationExams.pageSize)
  const currentPage = Number(paginationExams.currentPage)
  const end = currentPage * pageSize
  return Math.min(end, filteredExams.value.length)
})

const isValidJumpPageExams = computed(() => {
  return jumpPageExams.value >= 1 && jumpPageExams.value <= paginationExams.totalPages && jumpPageExams.value !== paginationExams.currentPage
})

// 观察者
watch(filteredClasses, () => {
  nextTick(() => {
    updatePagination()
  })
}, { immediate: true })

watch(() => pagination.pageSize, (newVal) => {
  if (typeof newVal !== 'number') {
    pagination.pageSize = Number(newVal)
  }
}, { immediate: true })

watch(filteredExams, () => {
  nextTick(() => {
    updatePaginationExams()
  })
}, { immediate: true })

watch(() => paginationExams.pageSize, (newVal) => {
  if (typeof newVal !== 'number') {
    paginationExams.pageSize = Number(newVal)
  }
}, { immediate: true })

// 定时器变量
let timeUpdateInterval = null

// 方法
const setActiveMenu = (index) => {
  for (let i = 0; i < menuItems.value.length; i++) {
    menuItems.value[i].active = i === index
  }
  currentPage.value = menuItems.value[index].page
}

const getDraftExamsCount = () => {
  return publishedExams.value.filter(exam => exam.status === 'DRAFT').length
}

const getPublishedExamsCount = () => {
  return publishedExams.value.filter(exam => exam.status === 'PUBLISHED').length
}

const getStatusText = (status) => {
  return status === 'DRAFT' ? '草稿' : '已发布'
}

const getStatusBadgeClass = (status) => {
  return status === 'DRAFT' ? 'status-draft' : 'status-published'
}

const getExamCardClass = (status) => {
  return status === 'DRAFT' ? 'exam-card-draft' : 'exam-card-published'
}

// API调用方法
const apiCall = (url, method, data) => {
  if (!window.Promise) {
    return {
      then: (success, error) => {
        if (error) error(new Error('浏览器不支持Promise API'))
      },
      catch: (error) => {
        if (error) error(new Error('浏览器不支持Promise API'))
      }
    }
  }

  return new Promise((resolve, reject) => {
    if (!window.fetch) {
      reject(new Error('浏览器不支持fetch API'))
      return
    }

    const config = {
      method: method,
      headers: {
        'Content-Type': 'application/json',
      }
    }

    if (data) {
      if (method === 'GET') {
        const params = new URLSearchParams(data)
        url += (url.indexOf('?') !== -1 ? '&' : '?') + params.toString()
      } else {
        config.body = JSON.stringify(data)
      }
    }

    fetch(url, config)
        .then(response => {
          if (!response.ok) {
            throw new Error('HTTP ' + response.status + ': ' + response.statusText)
          }
          return response.json()
        })
        .then(result => {
          const isSuccess = result.success === true ||
              result.code === 200 ||
              (result.message && result.message.indexOf('成功') !== -1) ||
              result.data !== undefined

          if (isSuccess) {
            resolve(result)
          } else {
            reject(new Error(result.message || '请求失败'))
          }
        })
        .catch(error => {
          if (error.message.indexOf('fetch') !== -1) {
            reject(new Error('网络连接失败，请检查网络或后端服务'))
          } else {
            reject(error)
          }
        })
  })
}

// 备用的发布考试API方法
const publishExamAPI_backup = async (examId, requestData) => {
  try {
    const response = await fetch(`http://localhost:8080/api/exams/${examId}/publish`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestData)
    })

    if (!response.ok) {
      const errorText = await response.text()
      throw new Error(`HTTP ${response.status}: ${errorText}`)
    }

    const result = await response.json()
    return result
  } catch (error) {
    console.error('发布考试API调用失败:', error)
    throw error
  }
}

// 加载用户信息
const loadUserInfo = () => {
  if (!window.Promise || !window.fetch) {
    userInfo.loading = false
    return
  }

  if (window.console && console.log) {
    console.log('开始加载用户信息，userId:', currentTeacherId.value)
  }

  apiCall('http://localhost:8080/api/users/' + currentTeacherId.value, 'GET')
      .then(response => {
        if (window.console && console.log) {
          console.log('获取到用户信息:', response)
        }

        if (response.data) {
          userInfo.id = response.data.id
          userInfo.username = response.data.username || '未知用户'
          userInfo.loading = false
        } else {
          userInfo.id = currentTeacherId.value
          userInfo.username = '用户'
          userInfo.loading = false
        }
      })
      .catch(error => {
        if (window.console && console.log) {
          console.error('获取用户信息失败:', error)
        }
        userInfo.id = currentTeacherId.value
        userInfo.username = '用户'
        userInfo.loading = false
      })
}

// 获取班级学生数量
const getClassStudentCount = (classId) => {
  if (!window.Promise) {
    return {
      then: (success) => {
        if (success) success(0)
      },
      catch: () => {
        // 忽略错误
      }
    }
  }

  return new Promise((resolve) => {
    if (!window.fetch) {
      resolve(0)
      return
    }

    const url = 'http://localhost:8080/api/class-teachers/getClassesStudentByClassId'

    if (window.console && console.log) {
      console.log('正在获取班级学生数量，classId:', classId, 'URL:', url)
    }

    const formData = new FormData()
    formData.append('classId', classId)

    fetch(url, {
      method: 'POST',
      body: formData
    })
        .then(response => {
          if (!response.ok) {
            throw new Error('HTTP ' + response.status + ': ' + response.statusText)
          }
          return response.json()
        })
        .then(result => {
          if (window.console && console.log) {
            console.log('班级', classId, '的API响应:', result)
          }

          if (result && result.code === 200 && result.data && Array.isArray(result.data)) {
            const studentCount = result.data.length

            if (window.console && console.log) {
              console.log('班级', classId, '的学生数量:', studentCount, '学生数据:', result.data)
            }

            resolve(studentCount)
          } else {
            if (window.console && console.log) {
              console.log('班级', classId, '的响应格式异常:', result)
            }
            resolve(0)
          }
        })
        .catch(error => {
          if (window.console && console.log) {
            console.error('获取班级', classId, '学生数量失败:', error)
          }
          resolve(0)
        })
  })
}

// 加载班级列表
const loadClasses = () => {
  loading.value = true

  if (!window.Promise || !window.fetch) {
    loading.value = false
    return
  }

  if (window.console && console.log) {
    console.log('开始加载班级数据，teacherId:', currentTeacherId.value)
  }

  apiCall('http://localhost:8080/api/class-teachers/getAllClassesByTeachersId?teacherId=' + currentTeacherId.value, 'GET')
      .then(classIdsResponse => {
        if (window.console && console.log) {
          console.log('获取到班级ID列表:', classIdsResponse)
        }

        classes.value = []

        if (classIdsResponse.data && classIdsResponse.data.length > 0) {
          let completedCount = 0
          const totalCount = classIdsResponse.data.length

          if (window.console && console.log) {
            console.log('需要加载', totalCount, '个班级的详细信息')
          }

          for (let i = 0; i < classIdsResponse.data.length; i++) {
            const classItem = classIdsResponse.data[i]

            apiCall('http://localhost:8080/api/classes/getClassById?classId=' + classItem.classId, 'GET')
                .then(classDetailResponse => {
                  if (classDetailResponse.data) {
                    const classData = {
                      class_id: classDetailResponse.data.classId,
                      name: classDetailResponse.data.name,
                      description: classDetailResponse.data.description,
                      createdAt: classDetailResponse.data.createdAt,
                      studentCount: 0
                    }

                    if (window.console && console.log) {
                      console.log('获取到班级详情:', classData.name, '(ID:', classData.class_id, ')')
                    }

                    getClassStudentCount(classDetailResponse.data.classId)
                        .then(studentCount => {
                          if (window.console && console.log) {
                            console.log('班级', classData.name, '(ID:', classData.class_id, ') 的学生数量:', studentCount)
                          }

                          classData.studentCount = studentCount
                          classes.value.push(classData)
                          completedCount++

                          if (window.console && console.log) {
                            console.log('已完成', completedCount, '/', totalCount, '个班级的数据加载')
                          }

                          if (completedCount === totalCount) {
                            loading.value = false
                            setTimeout(() => {
                              updatePagination()
                              if (window.console && console.log) {
                                console.log('所有班级数据加载完成:', classes.value)
                              }
                            }, 100)
                          }
                        })
                        .catch(() => {
                          if (window.console && console.log) {
                            console.log('班级', classData.name, '获取学生数量失败，设为0')
                          }

                          classData.studentCount = 0
                          classes.value.push(classData)
                          completedCount++

                          if (completedCount === totalCount) {
                            loading.value = false
                            setTimeout(() => {
                              updatePagination()
                            }, 100)
                          }
                        })
                  } else {
                    completedCount++
                    if (completedCount === totalCount) {
                      loading.value = false
                      setTimeout(() => {
                        updatePagination()
                      }, 100)
                    }
                  }
                })
                .catch(error => {
                  if (window.console && console.log) {
                    console.error('获取班级详情失败:', error)
                  }
                  completedCount++
                  if (completedCount === totalCount) {
                    loading.value = false
                    setTimeout(() => {
                      updatePagination()
                    }, 100)
                  }
                })
          }
        } else {
          loading.value = false
          setTimeout(() => {
            updatePagination()
          }, 100)
        }
      })
      .catch(error => {
        if (window.console && console.log) {
          console.error('获取班级ID列表失败:', error)
        }
        classes.value = []
        loading.value = false
        setTimeout(() => {
          updatePagination()
        }, 100)
      })
}

// 刷新单个班级的学生数量
const refreshClassStudentCount = (classId) => {
  if (!window.Promise) {
    return
  }

  getClassStudentCount(classId)
      .then(studentCount => {
        for (let i = 0; i < classes.value.length; i++) {
          if (classes.value[i].class_id === classId) {
            classes.value[i].studentCount = studentCount
            break
          }
        }
      })
      .catch(() => {
        // 忽略错误
      })
}

const getTotalStudents = () => {
  if (!filteredClasses.value || filteredClasses.value.length === 0) {
    return 0
  }
  let total = 0
  for (let i = 0; i < filteredClasses.value.length; i++) {
    total += (filteredClasses.value[i].studentCount || 0)
  }
  return total
}

// 获取所有班级的总学生数（用于主页面）
const getTotalStudentsAll = () => {
  if (!classes.value || classes.value.length === 0) {
    return 0
  }
  let total = 0
  for (let i = 0; i < classes.value.length; i++) {
    total += (classes.value[i].studentCount || 0)
  }
  return total
}

// 获取今日活动数量
const getRecentActivitiesCount = () => {
  const today = new Date().toLocaleDateString('zh-CN')
  let count = 0
  for (let i = 0; i < recentActivities.value.length; i++) {
    if (recentActivities.value[i].time.indexOf(today.replace(/\//g, '/')) !== -1) {
      count++
    }
  }
  return count > 0 ? count : Math.floor(Math.random() * 5) + 1
}

// 获取当前日期
const getCurrentDate = () => {
  const date = new Date()
  const options = {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  }
  return date.toLocaleDateString('zh-CN', options)
}

// 获取当前时间
const getCurrentTime = () => {
  const date = new Date()
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 刷新活动列表
const refreshActivities = () => {
  showSuccess('活动列表已刷新')

  const newActivity = {
    id: recentActivities.value.length + 1,
    type: 'system_update',
    title: '系统活动更新',
    description: '成功刷新了最新的活动信息',
    time: new Date().toLocaleString('zh-CN'),
    icon: 'edit',
    color: 'primary'
  }

  recentActivities.value.unshift(newActivity)

  if (recentActivities.value.length > 20) {
    recentActivities.value = recentActivities.value.slice(0, 20)
  }
}

const updatePagination = () => {
  const pageSize = Number(pagination.pageSize)
  pagination.totalPages = Math.ceil(filteredClasses.value.length / pageSize)

  if (pagination.currentPage > pagination.totalPages && pagination.totalPages > 0) {
    pagination.currentPage = 1
  }

  if (filteredClasses.value.length === 0) {
    pagination.currentPage = 1
    pagination.totalPages = 1
  }

  jumpPage.value = pagination.currentPage
}

const onPageSizeChange = () => {
  pagination.pageSize = Number(pagination.pageSize)
  pagination.currentPage = 1
  updatePagination()
}

const previousPage = () => {
  if (pagination.currentPage > 1) {
    pagination.currentPage--
    jumpPage.value = pagination.currentPage
  }
}

const nextPage = () => {
  if (pagination.currentPage < pagination.totalPages) {
    pagination.currentPage++
    jumpPage.value = pagination.currentPage
  }
}

const goToPage = (page) => {
  if (page >= 1 && page <= pagination.totalPages) {
    pagination.currentPage = page
    jumpPage.value = page
  }
}

const jumpToPage = () => {
  if (isValidJumpPage.value) {
    goToPage(jumpPage.value)
  }
}

const updatePaginationExams = () => {
  const pageSize = Number(paginationExams.pageSize)
  paginationExams.totalPages = Math.ceil(filteredExams.value.length / pageSize)

  if (paginationExams.currentPage > paginationExams.totalPages && paginationExams.totalPages > 0) {
    paginationExams.currentPage = 1
  }

  if (filteredExams.value.length === 0) {
    paginationExams.currentPage = 1
    paginationExams.totalPages = 1
  }

  jumpPageExams.value = paginationExams.currentPage
}

const onPageSizeChangeExams = () => {
  paginationExams.pageSize = Number(paginationExams.pageSize)
  paginationExams.currentPage = 1
  updatePaginationExams()
}

const previousPageExams = () => {
  if (paginationExams.currentPage > 1) {
    paginationExams.currentPage--
    jumpPageExams.value = paginationExams.currentPage
  }
}

const nextPageExams = () => {
  if (paginationExams.currentPage < paginationExams.totalPages) {
    paginationExams.currentPage++
    jumpPageExams.value = paginationExams.currentPage
  }
}

const goToPageExams = (page) => {
  if (page >= 1 && page <= paginationExams.totalPages) {
    paginationExams.currentPage = page
    jumpPageExams.value = page
  }
}

const jumpToPageExams = () => {
  if (isValidJumpPageExams.value) {
    goToPageExams(jumpPageExams.value)
  }
}

// 考试中心统计相关方法
const getTotalExamClasses = () => {
  let total = 0
  for (let i = 0; i < publishedExams.value.length; i++) {
    total += publishedExams.value[i].publishedClasses.length
  }
  return total
}

const resetClassForm = () => {
  classForm.class_id = null
  classForm.name = ''
  classForm.description = ''
}

const closeModals = () => {
  showCreateModal.value = false
  showEditModal.value = false
  showDeleteModal.value = false
  showInviteModal.value = false
  showCreateExamModal.value = false
  showDeletePublishModal.value = false
  showStudentsModal.value = false
  showAddStudentModal.value = false
  resetClassForm()
  resetExamForm()
  resetStudentsModal()
  resetAddStudentForm()
}

const resetStudentsModal = () => {
  studentsModalData.className = ''
  studentsModalData.classId = null
  studentsModalData.students = []
  studentsModalData.loading = false
}

const resetAddStudentForm = () => {
  addStudentForm.classId = ''
  addStudentForm.studentId = ''
  addStudentForm.loading = false
}

// 添加学生到班级
const addStudentToClass = () => {
  if (!addStudentForm.classId || !addStudentForm.studentId) {
    alert('请填写班级ID和学生ID')
    return
  }

  const classId = Number(addStudentForm.classId)
  const studentId = Number(addStudentForm.studentId)

  if (isNaN(classId) || isNaN(studentId) || classId <= 0 || studentId <= 0) {
    alert('请输入有效的班级ID和学生ID')
    return
  }

  addStudentForm.loading = true

  if (window.console && console.log) {
    console.log('开始添加学生到班级，classId:', classId, 'studentId:', studentId)
  }

  const formData = new FormData()
  formData.append('classId', classId)
  formData.append('studentId', studentId)

  fetch('http://localhost:8080/api/class-teachers/inviteStudentById', {
    method: 'POST',
    body: formData
  })
      .then(response => {
        if (!response.ok) {
          throw new Error('HTTP ' + response.status + ': ' + response.statusText)
        }
        return response.json()
      })
      .then(result => {
        if (window.console && console.log) {
          console.log('添加学生API响应:', result)
        }

        const isSuccess = result.success === true ||
            result.code === 200 ||
            (result.message && result.message.indexOf('成功') !== -1)

        if (isSuccess) {
          showSuccess('学生添加成功！')
          closeModals()

          setTimeout(() => {
            loadClasses()
          }, 500)
        } else {
          throw new Error(result.message || '添加学生失败')
        }
      })
      .catch(error => {
        if (window.console && console.log) {
          console.error('添加学生失败:', error)
        }
        showError('添加学生失败: ' + error.message)
      })
      .finally(() => {
        addStudentForm.loading = false
      })
}

// 查看班级学生
const viewStudents = (classItem) => {
  studentsModalData.className = classItem.name
  studentsModalData.classId = classItem.class_id
  studentsModalData.students = []
  studentsModalData.loading = true

  showStudentsModal.value = true

  loadClassStudents(classItem.class_id)
}

// 加载班级学生信息
const loadClassStudents = (classId) => {
  if (!window.Promise || !window.fetch) {
    studentsModalData.loading = false
    return
  }

  if (window.console && console.log) {
    console.log('开始加载班级学生信息，classId:', classId)
  }

  const formData = new FormData()
  formData.append('classId', classId)

  fetch('http://localhost:8080/api/class-teachers/getClassesStudentByClassId', {
    method: 'POST',
    body: formData
  })
      .then(response => {
        if (!response.ok) {
          throw new Error('HTTP ' + response.status + ': ' + response.statusText)
        }
        return response.json()
      })
      .then(result => {
        if (window.console && console.log) {
          console.log('获取到学生ID列表:', result)
        }

        if (result && result.code === 200 && result.data && Array.isArray(result.data)) {
          if (result.data.length === 0) {
            studentsModalData.students = []
            studentsModalData.loading = false
          } else {
            loadStudentDetails(result.data)
          }
        } else {
          if (window.console && console.log) {
            console.log('获取学生ID列表响应格式异常:', result)
          }
          studentsModalData.students = []
          studentsModalData.loading = false
        }
      })
      .catch(error => {
        if (window.console && console.log) {
          console.error('获取学生ID列表失败:', error)
        }
        studentsModalData.students = []
        studentsModalData.loading = false
        showError('获取学生列表失败: ' + error.message)
      })
}

// 加载学生详细信息
const loadStudentDetails = (studentDataList) => {
  const students = []
  let completedCount = 0
  const totalCount = studentDataList.length

  if (window.console && console.log) {
    console.log('需要加载', totalCount, '个学生的详细信息:', studentDataList)
  }

  for (let i = 0; i < studentDataList.length; i++) {
    const studentData = studentDataList[i]
    const studentId = studentData.studentId || studentData.student_id || studentData.id

    if (!studentId) {
      if (window.console && console.log) {
        console.log('学生数据中没有找到ID字段，使用原始数据:', studentData)
      }
      students.push({
        id: studentData.studentId || studentData.student_id || studentData.id || '未知',
        username: studentData.username || studentData.name || '未知学生',
        role: studentData.role || 'student'
      })
      completedCount++

      if (completedCount === totalCount) {
        studentsModalData.students = students
        studentsModalData.loading = false

        if (window.console && console.log) {
          console.log('所有学生信息加载完成:', students)
        }
      }
      continue
    }

    apiCall('http://localhost:8080/api/users/' + studentId, 'GET')
        .then(response => {
          if (window.console && console.log) {
            console.log('获取到学生详细信息:', response)
          }

          if (response.data) {
            students.push({
              id: response.data.id,
              username: response.data.username || '未知学生',
              role: response.data.role || 'student',
              email: response.data.email,
              gender: response.data.gender
            })
          } else {
            students.push({
              id: studentId,
              username: '未知学生',
              role: 'student'
            })
          }

          completedCount++

          if (completedCount === totalCount) {
            studentsModalData.students = students
            studentsModalData.loading = false

            if (window.console && console.log) {
              console.log('所有学生信息加载完成:', students)
            }
          }
        })
        .catch(error => {
          if (window.console && console.log) {
            console.error('获取学生', studentId, '详细信息失败:', error)
          }

          students.push({
            id: studentId,
            username: '获取失败',
            role: 'student'
          })

          completedCount++

          if (completedCount === totalCount) {
            studentsModalData.students = students
            studentsModalData.loading = false
          }
        })
  }
}

const createClass = () => {
  if (!classForm.name) {
    alert('请填写班级名称')
    return
  }

  const formData = new FormData()
  formData.append('className', classForm.name)
  formData.append('teacherId', currentTeacherId.value)
  if (classForm.description) {
    formData.append('description', classForm.description)
  }

  // 修改为完整URL路径
  fetch('http://localhost:8080/api/class-teachers/createClass', {
    method: 'POST',
    body: formData
  })
      .then(response => response.json())
      .then(result => {
        const isSuccess = result.success === true ||
            result.code === 200 ||
            (result.message && result.message.indexOf('成功') !== -1)

        if (isSuccess) {
          showSuccess('班级创建成功！')
          closeModals()

          setTimeout(() => {
            loadClasses()

            setTimeout(() => {
              updatePagination()
              const totalItems = filteredClasses.value.length
              const pageSize = Number(pagination.pageSize)
              const lastPage = Math.ceil(totalItems / pageSize)

              if (lastPage > pagination.currentPage) {
                pagination.currentPage = lastPage
                jumpPage.value = lastPage
              }
            }, 500)
          }, 100)
        } else {
          throw new Error(result.message || '创建班级失败')
        }
      })
      .catch(error => {
        showError('创建班级失败: ' + error.message)
      })
}

const editClass = (classItem) => {
  classForm.class_id = classItem.class_id
  classForm.name = classItem.name
  classForm.description = classItem.description || ''
  showEditModal.value = true
}

const updateClass = () => {
  if (!classForm.name || !classForm.name.trim()) {
    alert('请填写班级名称')
    return
  }

  const updateData = {
    classId: classForm.class_id,
    name: classForm.name.trim(),
    description: classForm.description ? classForm.description.trim() : ""
  }

  apiCall('http://localhost:8080/api/classes/updateClassById', 'POST', updateData)
      .then(() => {
        showSuccess('班级信息更新成功！')
        closeModals()

        setTimeout(() => {
          loadClasses()
        }, 100)
      })
      .catch(error => {
        showError('更新班级失败: ' + error.message)
      })
}

const confirmDeleteClass = (classItem) => {
  deleteTarget.value = classItem
  showDeleteModal.value = true
}

// 修复后的删除班级方法
const deleteClass = () => {
  if (!deleteTarget.value) return

  if (window.console && console.log) {
    console.log('开始删除班级:', deleteTarget.value.name, 'ID:', deleteTarget.value.class_id)
  }

  // 根据后端API，只发送classId参数
  const formData = new FormData()
  formData.append('classId', deleteTarget.value.class_id)

  if (window.console && console.log) {
    console.log('删除班级请求参数:', {
      classId: deleteTarget.value.class_id
    })
  }

  fetch('http://localhost:8080/api/class-teachers/deleteClass', {
    method: 'POST',
    body: formData
  })
      .then(response => {
        if (window.console && console.log) {
          console.log('删除班级响应状态:', response.status, response.statusText)
        }

        if (!response.ok) {
          throw new Error('HTTP ' + response.status + ': ' + response.statusText)
        }
        return response.json()
      })
      .then(result => {
        if (window.console && console.log) {
          console.log('删除班级API响应:', result)
          console.log('响应数据类型:', typeof result)
          console.log('响应字段:', Object.keys(result))
        }

        // 更宽泛的成功判断逻辑
        const isSuccess =
            // 检查常见的成功标识
            result.success === true ||
            result.code === 200 ||
            result.status === 200 ||
            result.status === 'success' ||
            // 检查消息中的成功标识
            (result.message && (
                result.message.includes('成功') ||
                result.message.includes('删除') ||
                result.message.includes('success') ||
                result.message.toLowerCase().includes('success')
            )) ||
            // 如果没有错误标识且HTTP状态正常，也视为成功
            (!result.error && !result.err && response.ok) ||
            // 检查data字段存在（某些API只返回data）
            (result.data !== undefined && result.data !== null)

        if (window.console && console.log) {
          console.log('成功判断结果:', isSuccess)
        }

        if (isSuccess) {
          showSuccess('班级删除成功！')
          showDeleteModal.value = false
          deleteTarget.value = null

          setTimeout(() => {
            loadClasses()
            setTimeout(() => {
              updatePagination()
              if (paginatedClasses.value.length === 0 && pagination.currentPage > 1) {
                pagination.currentPage = pagination.currentPage - 1
                jumpPage.value = pagination.currentPage
              }
              generateRecentActivities()
            }, 500)
          }, 100)
        } else {
          // 如果判断逻辑仍然失败，但HTTP状态是成功的，给出警告并执行成功逻辑
          if (response.ok) {
            if (window.console && console.warn) {
              console.warn('API响应格式异常，但HTTP状态正常，执行成功流程:', result)
            }
            showSuccess('班级删除成功！')
            showDeleteModal.value = false
            deleteTarget.value = null

            setTimeout(() => {
              loadClasses()
              setTimeout(() => {
                updatePagination()
                if (paginatedClasses.value.length === 0 && pagination.currentPage > 1) {
                  pagination.currentPage = pagination.currentPage - 1
                  jumpPage.value = pagination.currentPage
                }
                generateRecentActivities()
              }, 500)
            }, 100)
          } else {
            throw new Error(result.message || result.error || '删除班级失败')
          }
        }
      })
      .catch(error => {
        if (window.console && console.log) {
          console.error('删除班级失败详情:', error)
        }
        showError('删除班级失败: ' + error.message)
      })
}

// 修复后的获取邀请码方法
const getInviteCode = (className) => {
  if (window.console && console.log) {
    console.log('获取邀请码，班级名称:', className)
  }

  // 使用完整URL路径
  const formData = new FormData()
  formData.append('classname', className)

  fetch('http://localhost:8080/api/class-teachers/inviteStudentByInviteCode', {
    method: 'POST',
    body: formData
  })
      .then(response => {
        if (!response.ok) {
          throw new Error('HTTP ' + response.status + ': ' + response.statusText)
        }
        return response.json()
      })
      .then(result => {
        // 添加调试信息
        if (window.console && console.log) {
          console.log('获取邀请码API响应:', result)
        }

        const isSuccess = result.success === true ||
            result.code === 200 ||
            (result.message && result.message.indexOf('成功') !== -1)

        if (isSuccess) {
          const message = result.message || result.data || ''
          // 改进邀请码提取逻辑
          const inviteCodeMatch = message.match(/班级邀请码为[:：]\s*(.+)/)
          if (inviteCodeMatch && inviteCodeMatch[1]) {
            inviteCodeData.className = className
            inviteCodeData.code = inviteCodeMatch[1].trim()
            showInviteModal.value = true
          } else {
            // 如果没有匹配到特定格式，直接使用返回的消息
            inviteCodeData.className = className
            inviteCodeData.code = message.trim()
            showInviteModal.value = true
          }
        } else {
          throw new Error(result.message || '获取邀请码失败，请检查班级名称！')
        }
      })
      .catch(error => {
        if (window.console && console.log) {
          console.error('获取邀请码失败详情:', error)
        }
        showError('获取邀请码失败: ' + error.message)
      })
}

const copyInviteCode = () => {
  if (navigator.clipboard) {
    navigator.clipboard.writeText(inviteCodeData.code).then(() => {
      alert('✅ 邀请码已复制到剪贴板')
    }).catch(() => {
      alert('❌ 复制失败，请手动复制')
    })
  } else {
    const textArea = document.createElement('textarea')
    textArea.value = inviteCodeData.code
    document.body.appendChild(textArea)
    textArea.select()
    try {
      document.execCommand('copy')
      alert('✅ 邀请码已复制到剪贴板')
    } catch (err) {
      alert('❌ 复制失败，请手动复制')
    }
    document.body.removeChild(textArea)
  }
}

const formatDate = (dateString) => {
  if (!dateString) return '未知'
  try {
    const date = new Date(dateString)
    return date.toLocaleDateString('zh-CN')
  } catch (error) {
    return dateString
  }
}

const showSuccess = (message) => {
  alert('✅ ' + message)
}

const showError = (message) => {
  alert('❌ ' + message)
}

// 考试中心相关方法
const closeExamModals = () => {
  showCreateExamModal.value = false
  showDeletePublishModal.value = false
  resetExamForm()
}

const resetExamForm = () => {
  examForm.title = ''
  examForm.description = ''
  examForm.examTime = ''
  examForm.endTime = ''
  examForm.duration = ''
  examForm.selectedClasses = []
}

const createExam = async () => {
  if (!examForm.title || !examForm.examTime || !examForm.endTime || !examForm.duration) {
    alert('请填写所有必填项');
    return;
  }

  if (examForm.selectedClasses.length === 0) {
    alert('请至少选择一个班级');
    return;
  }

  const startTime = new Date(examForm.examTime);
  const endTime = new Date(examForm.endTime);
  if (endTime <= startTime) {
    alert('考试结束时间必须晚于开始时间');
    return;
  }

  try {
    // 为每个选中的班级创建考试
    const createPromises = examForm.selectedClasses.map(async (className) => {
      const selectedClass = classes.value.find(c => c.name === className);
      if (!selectedClass) {
        throw new Error(`未找到班级: ${className}`);
      }

      const examData = {
        teacherId: currentTeacherId.value,
        title: examForm.title,
        description: examForm.description || '',
        startTime: examForm.examTime,
        endTime: examForm.endTime,
        duration: parseInt(examForm.duration.replace(/[^\d]/g, '')),
        classId: selectedClass.class_id
      };

      const response = await fetch('http://localhost:8080/api/exams/create', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(examData)
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const result = await response.json();

      if (result.code !== 200) {
        throw new Error(result.message || '创建考试失败');
      }

      // 将 examId、classId 存入 localStorage
      const existingExamIds = JSON.parse(localStorage.getItem('examIds') || '[]');
      existingExamIds.push(result.data.examId);
      localStorage.setItem('examIds', JSON.stringify(existingExamIds)); // 使用examIds存储数组
      localStorage.setItem('currentExamId', result.data.examId.toString()); // 存储当前创建的examId
      localStorage.setItem('currentClassId', selectedClass.class_id.toString()); // 存储当前classId
      localStorage.setItem('teacherId', examData.teacherId.toString());

      return {
        examId: result.data.examId,
        className: className,
        ...examData
      };
    });

    const createdExams = await Promise.all(createPromises);

    showSuccess(`考试创建成功！共为 ${createdExams.length} 个班级创建了考试`);
    closeExamModals();

    setTimeout(() => {
      loadPublishedExams();
    }, 500);

  } catch (error) {
    console.error('创建考试失败:', error);
    showError('创建考试失败: ' + error.message);
  }
};

// 修复后的发布考试方法 - 简化错误处理逻辑
const publishExamFromCard = async (exam) => {
  try {
    // 检查考试状态
    if (exam.status === 'PUBLISHED') {
      showError('考试已经发布，无需重复发布')
      return
    }

    console.log('开始发布考试:', exam)

    const examId = exam.id
    const teacherId = Number(localStorage.getItem('id') || currentTeacherId.value)
    const classId = exam.classId

    if (!examId || !teacherId) {
      showError('考试信息不完整，无法发布')
      return
    }

    // 构建请求参数
    const requestData = {
      teacherId: teacherId,
      classIds: []
    }

    // 处理班级ID
    if (classId && classId !== 0 && classId !== null && classId !== undefined) {
      requestData.classIds.push(Number(classId))
    } else {
      // 如果没有classId，尝试从localStorage获取
      const storedClassId = localStorage.getItem('currentClassId')
      if (storedClassId && storedClassId !== '0') {
        requestData.classIds.push(Number(storedClassId))
      }
    }

    console.log('发布考试请求数据:', requestData)

    // 调用发布API
    const response = await fetch(`http://localhost:8080/api/exams/${examId}/publish`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestData)
    })

    console.log('发布考试响应状态:', response.status)

    // 简化的成功判断逻辑 - 只要HTTP状态是2xx就认为成功
    if (response.ok) {
      showSuccess('考试发布成功')
      // 更新考试状态
      exam.status = 'PUBLISHED'
      // 重新加载考试列表
      setTimeout(() => {
        loadPublishedExams()
      }, 1000)
    } else {
      // 尝试获取错误信息
      let errorMessage = `发布失败 (HTTP ${response.status})`
      try {
        const result = await response.json()
        if (result.message) {
          errorMessage = result.message
        }
      } catch (e) {
        // 如果无法解析JSON，使用默认错误消息
      }
      throw new Error(errorMessage)
    }

  } catch (error) {
    console.error('发布考试失败:', error)
    showError('发布考试失败: ' + error.message)
  }
}

// 选择习题资源
const gotoQuestions = (examId) => {
  console.log('跳转到习题资源，examId:', examId)

  // 确保examId以正确的格式存储
  if (examId) {
    localStorage.setItem('examId', examId.toString())
    localStorage.setItem('currentExamId', examId.toString()) // 添加单个examId的存储
  }

  router.push('/questions')
}

const confirmDeletePublish = (item) => {
  deletePublishTarget.value = item
  showDeletePublishModal.value = true
}

const deletePublishedExam = () => {
  if (!deletePublishTarget.value) return

  // TODO: 调用后端API删除考试
  // 目前先从本地列表中删除，如果有后端删除接口，可以在这里调用
  for (let i = 0; i < publishedExams.value.length; i++) {
    if (publishedExams.value[i].id === deletePublishTarget.value.id) {
      publishedExams.value.splice(i, 1)
      break
    }
  }

  showSuccess('考试删除成功！')
  showDeletePublishModal.value = false
  deletePublishTarget.value = null

  // 重新加载已创建的考试列表（如果有后端删除接口）
  // setTimeout(() => {
  //   loadPublishedExams()
  // }, 500)

  updatePaginationExams()
}

const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  try {
    const date = new Date(dateTimeString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    }).replace(/\//g, '/')
  } catch (error) {
    return dateTimeString
  }
}

// 生命周期钩子
onMounted(() => {
  pagination.pageSize = Number(pagination.pageSize)
  pagination.currentPage = Number(pagination.currentPage)

  paginationExams.pageSize = Number(paginationExams.pageSize)
  paginationExams.currentPage = Number(paginationExams.currentPage)
  updatePaginationExams()

  // 测试API连接
  setTimeout(() => {
    loadUserInfo()
    loadClasses()
    loadPublishedExams()
  }, 100)

  // 设置定时器更新时间显示（每分钟更新一次）
  timeUpdateInterval = setInterval(() => {
    // 强制重新渲染时间显示
    nextTick()
  }, 60000)
})

onUnmounted(() => {
  if (timeUpdateInterval) {
    clearInterval(timeUpdateInterval)
  }
})
</script>

<style scoped>
.exam-stats-container {
  padding: 20px 16px;
}

.exam-stats {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  gap: 16px;
  text-align: center;
}

.exam-stats .stat-item {
  flex-direction: column;
}

.published-grid {
  grid-template-columns: 1fr;
  gap: 16px;
}

.modal-large {
  max-width: 800px;
  width: 90%;
}

/* 新的考试页面布局样式 */
.exam-header-layout {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
  padding: 20px 24px;
  background: white;
  border-radius: 8px;
  border: 1px solid #E2E8F0;
  box-shadow: 0px 4px 16px rgba(0, 0, 0, 0.08);
  gap: 24px;
  flex-wrap: wrap;
}

.exam-actions-left {
  display: flex;
  gap: 12px;
  align-items: center;
}

.exam-search-center {
  flex: 1;
  display: flex;
  justify-content: center;
  min-width: 240px;
}

.exam-stats-right {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 12px 20px;
  background: #F8FAFC;
  border-radius: 8px;
  border: 1px solid #E5E7EB;
  flex-shrink: 0;
}

.exam-stats-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.exam-stat-number {
  font-weight: 700;
  font-size: 20px;
  line-height: 28px;
  color: #1E293B;
}

.exam-stat-text {
  font-weight: 400;
  font-size: 12px;
  line-height: 16px;
  color: #64748B;
  white-space: nowrap;
}

.exam-stat-divider {
  width: 1px;
  height: 32px;
  background: #E5E7EB;
}

/* 状态徽章样式 */
.card-badges {
  display: flex;
  gap: 8px;
  align-items: center;
  flex-wrap: wrap;
}

.status-badge {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.status-badge.status-draft {
  background: #FEF3C7;
  color: #D97706;
  border: 1px solid #F59E0B;
}

.status-badge.status-published {
  background: #DCFCE7;
  color: #16A34A;
  border: 1px solid #22C55E;
}

/* 考试卡片状态样式 */
.exam-card-draft {
  border-left: 4px solid #F59E0B;
}

.exam-card-published {
  border-left: 4px solid #22C55E;
}

.exam-card-draft:hover {
  border-left-color: #D97706;
}

.exam-card-published:hover {
  border-left-color: #16A34A;
}

/* 主页面统计详情样式 */
.stat-detail {
  display: flex;
  gap: 8px;
  margin-top: 4px;
}

.stat-sub {
  font-size: 11px;
  color: #64748B;
  background: #F1F5F9;
  padding: 2px 6px;
  border-radius: 8px;
}

/* 学生信息模态框样式 */
.students-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #64748B;
}

.students-loading .loading-spinner {
  margin-bottom: 16px;
}

.empty-students {
  text-align: center;
  padding: 40px;
  color: #64748B;
}

.empty-students .empty-icon {
  margin-bottom: 16px;
  opacity: 0.6;
}

.empty-students .empty-text {
  font-size: 16px;
  margin: 0;
}

.students-header {
  padding: 16px 0;
  border-bottom: 1px solid #E2E8F0;
  margin-bottom: 20px;
}

.students-count {
  font-weight: 600;
  font-size: 16px;
  color: #4318D1;
  background: #F8F7FF;
  padding: 6px 16px;
  border-radius: 20px;
}

.students-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  max-height: 400px;
  overflow-y: auto;
  padding: 8px;
}

.student-card {
  background: #F8FAFC;
  border: 1px solid #E2E8F0;
  border-radius: 8px;
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 12px;
  transition: all 0.3s;
}

.student-card:hover {
  transform: translateY(-2px);
  box-shadow: 0px 8px 24px rgba(0, 0, 0, 0.12);
  border-color: #4318D1;
}

.student-avatar {
  width: 40px;
  height: 40px;
  background: #FEF7FF;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.student-info {
  flex: 1;
  min-width: 0;
}

.student-name {
  font-weight: 600;
  font-size: 16px;
  line-height: 24px;
  color: #1E293B;
  margin-bottom: 4px;
  word-break: break-word;
}

.student-id {
  font-weight: 500;
  font-size: 14px;
  line-height: 20px;
  color: #4318D1;
  margin-bottom: 2px;
}

.student-role {
  font-weight: 400;
  font-size: 12px;
  line-height: 16px;
  color: #64748B;
  background: #F1F5F9;
  padding: 2px 8px;
  border-radius: 12px;
  display: inline-block;
}

.checkbox-group {
  max-height: 150px;
}

.education-dashboard {
  position: relative;
  width: 100vw;
  min-height: 100vh;
  font-family: 'Inter', sans-serif;
  background: white;
  overflow-x: hidden;
  box-sizing: border-box;
}

.background-gradient {
  position: fixed;
  width: 100vw;
  height: 100vh;
  left: 0px;
  top: 0px;
  background: linear-gradient(90deg, #E2E8F0 100%, #F1F5F9 50%, #F8FAFC 0%);
  z-index: 1;
  pointer-events: none;
}

/* 顶部导航栏 */
.top-navbar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 73px;
  background: #FFFFFF;
  border-bottom: 0.8px solid #E2E8F0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  z-index: 100;
  box-sizing: border-box;
  box-shadow: 0px 2px 8px rgba(0, 0, 0, 0.08);
}

.nav-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.nav-icon {
  width: 36px;
  height: 36px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-inner {
  width: 13.33px;
  height: 10px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 2px solid #E2E8F0;
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.user-name {
  font-weight: 600;
  font-size: 14px;
  line-height: 20px;
  color: #1E293B;
}

.user-name.loading {
  color: #64748B;
  font-weight: 400;
}

.user-id {
  font-weight: 400;
  font-size: 12px;
  line-height: 16px;
  color: #64748B;
}

.nav-tabs {
  display: flex;
  gap: 24px;
}

.nav-tab {
  font-weight: 500;
  font-size: 16px;
  line-height: 24px;
  color: #475569;
  cursor: pointer;
  transition: color 0.3s;
}

.nav-tab:hover {
  color: #1E293B;
}

.nav-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.settings-btn {
  background: #FAF8FF;
  border-radius: 6px;
  padding: 8px 16px;
  font-weight: 500;
  font-size: 14px;
  line-height: 20px;
  color: #000000;
  cursor: pointer;
}

.menu-icon {
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.menu-line {
  width: 1.67px;
  height: 13.33px;
}

/* 左侧边栏 */
.sidebar {
  position: fixed;
  top: 60px; /* 和导航栏高度一致 */
  left: 0;
  width: 280px;
  height: calc(100vh - 73px); /* 减去导航栏高度 */
  background: #FFFFFF;
  border-right: 0.8px solid #E2E8F0;
  z-index: 90;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.sidebar-header {
  padding: 28px 24px;
  border-bottom: 0.8px solid #E2E8F0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.system-logo {
  width: 40px;
  height: 40px;
  background: linear-gradient(90deg, #E2E8F0 100%, #F1F5F9 50%, #F8FAFC 0%);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo-icon {
  width: 18px;
  height: 14.25px;
}

.system-title {
  font-weight: 700;
  font-size: 18px;
  line-height: 28px;
  color: #1E293B;
  margin: 0;
}

.system-subtitle {
  font-weight: 400;
  font-size: 14px;
  line-height: 20px;
  color: #64748B;
  margin: 0;
}

.sidebar-nav {
  flex: 1;
  padding: 16px;
}

.nav-item {
  width: 248px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 0 16px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.nav-item.active {
  background: linear-gradient(90deg, #E2E8F0 100%, #F1F5F9 50%, #F8FAFC 0%);
}

.nav-item:hover:not(.active) {
  background: #F8FAFC;
}

.nav-icon {
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-text {
  font-weight: 500;
  font-size: 16px;
  line-height: 24px;
  color: #000000;
}

/* 图标样式 */
.icon-home, .icon-students, .icon-courses, .icon-exam {
  width: 15px;
  height: 15px;
}

.sidebar-footer {
  padding: 16px;
  border-top: 0.8px solid #E2E8F0;
}

.help-card {
  background: #F8FAFC;
  border-radius: 8px;
  padding: 18px 16px;
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.help-icon {
  width: 32px;
  height: 32px;
  background: #FEF7FF;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.help-icon-inner {
  width: 12px;
  height: 12px;
}

.help-title {
  font-weight: 600;
  font-size: 14px;
  line-height: 20px;
  color: #1E293B;
  margin: 0;
}

.help-desc {
  font-weight: 400;
  font-size: 12px;
  line-height: 16px;
  color: #64748B;
  margin: 0;
}

.help-link {
  background: none;
  border: none;
  font-weight: 500;
  font-size: 14px;
  line-height: 20px;
  color: #4318D1;
  cursor: pointer;
  padding: 0;
}

/* 主内容区域 */
.main-content {
  position: absolute;
  top: 45px;
  left: 280px;
  right: 0;
  bottom: 0;
  padding: 32px;
  z-index: 5;
  min-height: calc(100vh - 73px);
  width: calc(100vw - 280px);
  max-width: calc(100vw - 280px);
  box-sizing: border-box;
  overflow-x: hidden;
}

.page-header {
  margin-bottom: 32px;
}

.page-title {
  font-weight: 700;
  font-size: 24px;
  line-height: 32px;
  color: #1E293B;
  margin: 0 0 9px 0;
}

.page-subtitle {
  font-weight: 400;
  font-size: 16px;
  line-height: 24px;
  color: #64748B;
  margin: 0;
}

/* 合并后的操作栏和统计信息样式 */
.combined-actions-stats {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
  padding: 20px 24px;
  background: white;
  border-radius: 8px;
  border: 1px solid #E2E8F0;
  box-shadow: 0px 4px 16px rgba(0, 0, 0, 0.08);
  gap: 24px;
  flex-wrap: wrap;
}

.actions-left {
  display: flex;
  gap: 12px;
  align-items: center;
}

.inline-stats {
  display: flex;
  align-items: center;
  gap: 24px;
  padding: 16px 24px;
  background: #F8FAFC;
  border-radius: 8px;
  border: 1px solid #E5E7EB;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.stat-number {
  font-weight: 700;
  font-size: 20px;
  line-height: 28px;
  color: #1E293B;
}

.stat-text {
  font-weight: 400;
  font-size: 12px;
  line-height: 16px;
  color: #64748B;
  white-space: nowrap;
}

.stat-divider {
  width: 1px;
  height: 32px;
  background: #E5E7EB;
}

.search-box {
  position: relative;
  width: 240px;
  flex-shrink: 0;
}

.search-input {
  width: 100%;
  height: 40px;
  border: 1px solid #E2E8F0;
  border-radius: 8px;
  padding: 0 16px 0 40px;
  font-size: 14px;
  color: #1E293B;
  background: white;
  transition: border-color 0.3s;
}

.search-input:focus {
  outline: none;
  border-color: #4318D1;
}

.search-icon {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  pointer-events: none;
}

/* 分页设置 */
.pagination-settings {
  display: flex;
  align-items: center;
  gap: 8px;
  white-space: nowrap;
}

.pagination-label {
  font-weight: 400;
  font-size: 14px;
  color: #64748B;
}

.pagination-select {
  padding: 6px 12px;
  border: 1px solid #E2E8F0;
  border-radius: 6px;
  background: white;
  font-size: 14px;
  color: #1E293B;
  cursor: pointer;
}

.pagination-select:focus {
  outline: none;
  border-color: #4318D1;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #64748B;
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid #E2E8F0;
  border-top: 2px solid #4318D1;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-right: 8px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 40px;
  color: #64748B;
}

.empty-icon {
  margin-bottom: 16px;
  opacity: 0.6;
}

.empty-text {
  font-size: 16px;
  margin-bottom: 20px;
}

.class-list {
  background: white;
  border-radius: 8px;
  border: 1px solid #E2E8F0;
  box-shadow: 0px 4px 16px rgba(0, 0, 0, 0.08);
  padding: 24px;
  width: 100%;
  box-sizing: border-box;
  overflow-x: hidden;
}

.class-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
  margin-bottom: 32px;
  width: 100%;
  align-items: stretch;
}

.class-card {
  background: #F8FAFC;
  border: 1px solid #E2E8F0;
  border-radius: 8px;
  padding: 18px;
  transition: all 0.3s;
  width: 100%;
  box-sizing: border-box;
  min-width: 0;
  display: flex;
  flex-direction: column;
  height: fit-content;
}

.class-card:hover {
  transform: translateY(-2px);
  box-shadow: 0px 8px 24px rgba(0, 0, 0, 0.12);
}

.class-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 14px;
}

.class-name {
  font-weight: 600;
  font-size: 18px;
  line-height: 28px;
  color: #1E293B;
  margin: 0 0 4px 0;
}

.class-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 18px;
  flex: 1;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-label {
  font-weight: 400;
  font-size: 14px;
  color: #64748B;
}

.detail-value {
  font-weight: 500;
  font-size: 14px;
  color: #1E293B;
}

.detail-value.student-count {
  color: #4318D1;
  font-weight: 600;
  background: #F8F7FF;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 13px;
}

.class-actions-buttons {
  display: flex;
  gap: 6px;
  flex-wrap: nowrap;
  justify-content: space-between;
  margin-top: 16px;
}

.btn-action {
  flex: 1;
  padding: 6px 8px;
  font-size: 12px;
  font-weight: 500;
  line-height: 16px;
  min-width: 0;
  white-space: nowrap;
  border-radius: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.btn-action svg {
  width: 12px;
  height: 12px;
  flex-shrink: 0;
}

/* 分页容器 */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
  padding: 24px 0 0 0;
  border-top: 1px solid #E2E8F0;
  flex-wrap: wrap;
}

.pagination-info {
  display: flex;
  align-items: center;
  white-space: nowrap;
}

.pagination-text {
  font-size: 14px;
  color: #64748B;
}

/* 分页控制 */
.pagination-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 12px;
  border: 1px solid #E2E8F0;
  border-radius: 6px;
  background: white;
  color: #475569;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  min-width: 40px;
  justify-content: center;
}

.pagination-btn:hover:not(:disabled) {
  background: #F8FAFC;
  border-color: #CBD5E1;
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination-btn-page.active {
  background: #4318D1;
  color: white;
  border-color: #4318D1;
}

.pagination-btn-page.active:hover {
  background: #3311B8;
  border-color: #3311B8;
}

.pagination-pages {
  display: flex;
  align-items: center;
  gap: 4px;
}

.pagination-ellipsis {
  padding: 8px 4px;
  color: #64748B;
  font-size: 14px;
}

/* 快速跳转 */
.pagination-jumper {
  display: flex;
  align-items: center;
  gap: 8px;
  white-space: nowrap;
}

.pagination-input {
  width: 60px;
  height: 32px;
  padding: 4px 8px;
  border: 1px solid #E2E8F0;
  border-radius: 4px;
  text-align: center;
  font-size: 14px;
}

.pagination-input:focus {
  outline: none;
  border-color: #4318D1;
}

/* 按钮样式 */
.btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border-radius: 6px;
  font-weight: 500;
  font-size: 14px;
  line-height: 20px;
  cursor: pointer;
  transition: all 0.3s;
  border: none;
  text-decoration: none;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  background: #F1F5F9 !important;
  color: #94A3B8 !important;
  border-color: #E2E8F0 !important;
}

.btn-sm {
  padding: 6px 12px;
  font-size: 12px;
}

.btn-primary {
  background: #4318D1;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #3311B8;
}

.btn-success {
  background: #059669;
  color: white;
}

.btn-success:hover:not(:disabled) {
  background: #047857;
}

.btn-secondary {
  background: #F1F5F9;
  color: #475569;
  border: 1px solid #E2E8F0;
}

.btn-secondary:hover:not(:disabled) {
  background: #E2E8F0;
}

.btn-info {
  background: #0EA5E9;
  color: white;
}

.btn-info:hover:not(:disabled) {
  background: #0284C7;
}

.btn-outline {
  background: transparent;
  color: #4318D1;
  border: 1px solid #4318D1;
}

.btn-outline:hover:not(:disabled) {
  background: #4318D1;
  color: white;
}

.btn-danger {
  background: #DC2626;
  color: white;
}

.btn-danger:hover:not(:disabled) {
  background: #B91C1C;
}

.btn-warning {
  background: #F59E0B;
  color: white;
}

.btn-warning:hover:not(:disabled) {
  background: #D97706;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0px 20px 25px rgba(0, 0, 0, 0.1);
}

.modal-small {
  max-width: 400px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 24px 0 24px;
  margin-bottom: 24px;
}

.modal-title {
  font-weight: 600;
  font-size: 18px;
  line-height: 28px;
  color: #1E293B;
  margin: 0;
}

.modal-close {
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  color: #64748B;
  transition: all 0.3s;
}

.modal-close:hover {
  background: #F1F5F9;
  color: #1E293B;
}

.modal-body {
  padding: 0 24px;
  margin-bottom: 24px;
}

.modal-form {
  padding: 0 24px;
}

.form-group {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  font-weight: 500;
  font-size: 14px;
  line-height: 20px;
  color: #1E293B;
  margin-bottom: 8px;
}

.form-input, .form-select, .form-textarea {
  width: 100%;
  border: 1px solid #E2E8F0;
  border-radius: 6px;
  padding: 8px 12px;
  font-size: 14px;
  color: #1E293B;
  background: white;
  transition: border-color 0.3s;
  box-sizing: border-box;
  font-family: inherit;
}

.form-input, .form-select {
  height: 40px;
}

.form-textarea {
  resize: vertical;
  min-height: 80px;
}

.form-input:focus, .form-select:focus, .form-textarea:focus {
  outline: none;
  border-color: #4318D1;
}

.form-help {
  font-size: 12px;
  color: #64748B;
  margin-top: 4px;
  line-height: 1.4;
}

.modal-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  padding: 24px;
  border-top: 1px solid #E2E8F0;
  margin-top: 24px;
}

/* 邀请码样式 */
.invite-code {
  background: #F8FAFC;
  border: 2px dashed #E2E8F0;
  border-radius: 8px;
  padding: 16px;
  text-align: center;
  font-family: 'Courier New', monospace;
  font-size: 18px;
  font-weight: 700;
  color: #4318D1;
  margin: 16px 0;
  letter-spacing: 2px;
}

.invite-note {
  font-size: 12px;
  color: #64748B;
  text-align: center;
  margin-top: 12px;
}

.published-content {
  background: white;
  border-radius: 8px;
  border: 1px solid #E2E8F0;
  box-shadow: 0px 4px 16px rgba(0, 0, 0, 0.08);
  padding: 24px;
  width: 100%;
  box-sizing: border-box;
  overflow-x: hidden;
}

.content-section {
  margin-bottom: 40px;
}

.content-section:last-child {
  margin-bottom: 0;
}

.section-title {
  font-weight: 600;
  font-size: 18px;
  line-height: 28px;
  color: #1E293B;
  margin: 0 0 20px 0;
  padding-bottom: 8px;
  border-bottom: 2px solid #E2E8F0;
}

.published-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  width: 100%;
}

.published-card {
  background: #F8FAFC;
  border: 1px solid #E2E8F0;
  border-radius: 8px;
  padding: 20px;
  transition: all 0.3s;
  width: 100%;
  box-sizing: border-box;
  min-width: 0;
}

.published-card:hover {
  transform: translateY(-2px);
  box-shadow: 0px 8px 24px rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.card-title {
  font-weight: 600;
  font-size: 16px;
  line-height: 24px;
  color: #1E293B;
  margin: 0 0 8px 0;
}

.card-type {
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 12px;
  font-weight: 500;
  white-space: nowrap;
}

.exam-type {
  background: #FEF3C7;
  color: #D97706;
}

.resource-type {
  background: #DBEAFE;
  color: #2563EB;
}

.card-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 20px;
}

.card-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  flex-wrap: wrap;
}

.card-actions .btn-sm {
  padding: 4px 8px;
  font-size: 11px;
  min-width: 60px;
}

/* 表单样式增强 */
.form-row {
  display: flex;
  gap: 16px;
}

.form-row .form-group {
  flex: 1;
}

.checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-height: 200px;
  overflow-y: auto;
  padding: 12px;
  border: 1px solid #E2E8F0;
  border-radius: 6px;
  background: #F8FAFC;
}

.checkbox-item {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.checkbox-input {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.checkbox-label {
  font-size: 14px;
  color: #1E293B;
  cursor: pointer;
}

.modal-large {
  max-width: 600px;
}

.modal-compact {
  max-width: 450px;
  width: 85%;
}

.modal-minimal {
  max-width: 380px;
  width: 80%;
}

.modal-header-minimal {
  padding: 12px 16px 0 16px;
  margin-bottom: 12px;
}

.modal-title-minimal {
  font-size: 16px;
  font-weight: 600;
}

.modal-form-minimal {
  padding: 0 16px;
}

.form-group-minimal {
  margin-bottom: 10px;
}

.form-label-minimal {
  font-size: 12px;
  margin-bottom: 4px;
  font-weight: 500;
}

.form-input-minimal, .form-textarea-minimal {
  height: 32px;
  padding: 4px 8px;
  font-size: 12px;
  border: 1px solid #E2E8F0;
}

.form-textarea-minimal {
  height: auto;
  min-height: 50px;
  resize: vertical;
}

.form-row-minimal {
  display: flex;
  gap: 8px;
}

.checkbox-group-minimal {
  max-height: 100px;
  padding: 6px 8px;
  gap: 6px;
  border: 1px solid #E2E8F0;
  border-radius: 4px;
  background: #F8FAFC;
  overflow-y: auto;
}

.checkbox-item-minimal {
  gap: 4px;
}

.checkbox-label-minimal {
  font-size: 12px;
}

.modal-actions-minimal {
  padding: 12px 16px;
  margin-top: 12px;
  gap: 8px;
  border-top: 1px solid #E2E8F0;
}

.btn-minimal {
  padding: 4px 12px;
  font-size: 12px;
  min-width: 60px;
  height: 28px;
}

.modal-compact .modal-header {
  padding: 16px 20px 0 20px;
  margin-bottom: 16px;
}

.modal-compact .modal-form {
  padding: 0 20px;
}

.form-group {
  margin-bottom: 16px;
}

.modal-compact .form-group {
  margin-bottom: 12px;
}

.form-input-compact, .form-textarea-compact {
  height: 36px;
  padding: 6px 10px;
  font-size: 13px;
}

.form-textarea-compact {
  height: auto;
  min-height: 60px;
  resize: vertical;
}

.form-row-compact {
  gap: 12px;
}

.checkbox-group-compact {
  max-height: 120px;
  padding: 8px 10px;
  gap: 8px;
}

.checkbox-group-compact .checkbox-item {
  gap: 6px;
}

.checkbox-group-compact .checkbox-label {
  font-size: 13px;
}

.modal-actions-compact {
  padding: 16px 20px;
  margin-top: 16px;
  gap: 10px;
}

.btn-compact {
  padding: 6px 14px;
  font-size: 13px;
  min-width: 70px;
}

/* 主页面样式 */
.welcome-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 32px;
  margin-bottom: 32px;
  color: white;
  position: relative;
  overflow: hidden;
}

.welcome-section::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 200px;
  height: 200px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  transform: translate(50%, -50%);
}

.welcome-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  position: relative;
  z-index: 2;
}

.welcome-title {
  font-size: 28px;
  font-weight: 700;
  margin: 0 0 8px 0;
  color: white;
}

.welcome-subtitle {
  font-size: 16px;
  margin: 0;
  opacity: 0.9;
  color: white;
}

.welcome-time {
  text-align: right;
  opacity: 0.9;
}

.current-date {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 4px;
}

.current-time {
  font-size: 24px;
  font-weight: 700;
}

/* 快速统计 */
.quick-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 32px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 16px;
  border: 1px solid #E2E8F0;
  box-shadow: 0px 4px 16px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0px 8px 24px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.stat-icon-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.stat-icon-success {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
  color: white;
}

.stat-icon-info {
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  color: white;
}

.stat-icon-warning {
  background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
  color: white;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: #1E293B;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #64748B;
  font-weight: 500;
}

/* 主要内容布局 */
.home-main-content {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 32px;
  align-items: start;
}

/* 活动区域 */
.activity-section, .quick-actions {
  background: white;
  border-radius: 12px;
  border: 1px solid #E2E8F0;
  box-shadow: 0px 4px 16px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 24px 0 24px;
  margin-bottom: 20px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #1E293B;
  margin: 0;
}

/* 活动时间线 */
.activity-timeline {
  padding: 0 24px;
  max-height: 480px;
  overflow-y: auto;
}

.activity-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px 0;
  border-bottom: 1px solid #F1F5F9;
  position: relative;
}

.activity-item:last-child {
  border-bottom: none;
}

.activity-item::before {
  content: '';
  position: absolute;
  left: 7px;
  top: 48px;
  bottom: -1px;
  width: 2px;
  background: #E2E8F0;
}

.activity-item:last-child::before {
  display: none;
}

.activity-icon {
  width: 32px;
  height: 32px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  position: relative;
  z-index: 2;
}

.activity-primary .activity-icon {
  background: #EEF2FF;
  color: #4F46E5;
}

.activity-success .activity-icon {
  background: #ECFDF5;
  color: #059669;
}

.activity-info .activity-icon {
  background: #EFF6FF;
  color: #2563EB;
}

.activity-warning .activity-icon {
  background: #FFFBEB;
  color: #D97706;
}

.activity-secondary .activity-icon {
  background: #F8FAFC;
  color: #64748B;
}

.activity-content {
  flex: 1;
  min-width: 0;
}

.activity-title {
  font-weight: 600;
  font-size: 14px;
  color: #1E293B;
  margin-bottom: 4px;
}

.activity-description {
  font-size: 13px;
  color: #64748B;
  margin-bottom: 6px;
  line-height: 1.4;
}

.activity-time {
  font-size: 12px;
  color: #94A3B8;
}

.activity-footer {
  padding: 16px 24px;
  text-align: center;
  border-top: 1px solid #F1F5F9;
}

/* 快捷操作 */
.action-grid {
  display: grid;
  gap: 16px;
  padding: 0 24px 24px 24px;
}

.action-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  border: 1px solid #E2E8F0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.action-card:hover {
  border-color: #4318D1;
  background: #F8F7FF;
  transform: translateY(-1px);
}

.action-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.action-icon-primary {
  background: #EEF2FF;
  color: #4F46E5;
}

.action-icon-success {
  background: #ECFDF5;
  color: #059669;
}

.action-icon-info {
  background: #EFF6FF;
  color: #2563EB;
}

.action-icon-warning {
  background: #FFFBEB;
  color: #D97706;
}

.action-content {
  flex: 1;
}

.action-title {
  font-weight: 600;
  font-size: 14px;
  color: #1E293B;
  margin-bottom: 2px;
}

.action-desc {
  font-size: 12px;
  color: #64748B;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .home-main-content {
    grid-template-columns: 1fr;
    gap: 24px;
  }

  .quick-stats {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
  }

  .exam-header-layout {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }

  .exam-search-center {
    order: 1;
  }

  .exam-actions-left {
    order: 2;
    justify-content: center;
  }

  .exam-stats-right {
    order: 3;
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .welcome-section {
    padding: 24px 20px;
  }

  .welcome-header {
    flex-direction: column;
    gap: 16px;
  }

  .welcome-time {
    text-align: left;
  }

  .welcome-title {
    font-size: 24px;
  }

  .quick-stats {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .stat-card {
    padding: 20px 16px;
  }

  .section-header {
    padding: 20px 20px 0 20px;
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .activity-timeline {
    padding: 0 20px;
  }

  .action-grid {
    padding: 0 20px 20px 20px;
  }

  .exam-header-layout {
    padding: 16px;
    gap: 12px;
  }

  .exam-actions-left {
    flex-direction: column;
    gap: 8px;
    width: 100%;
  }

  .exam-actions-left .btn {
    width: 100%;
    justify-content: center;
  }

  .exam-stats-right {
    flex-direction: column;
    gap: 12px;
    padding: 12px 16px;
  }

  .exam-stat-divider {
    width: 100%;
    height: 1px;
  }

  .card-badges {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
}

@media (max-width: 480px) {
  .welcome-section {
    padding: 20px 16px;
  }

  .welcome-title {
    font-size: 20px;
  }

  .current-time {
    font-size: 20px;
  }

  .stat-card {
    padding: 16px;
    gap: 12px;
  }

  .stat-icon {
    width: 40px;
    height: 40px;
  }

  .stat-number {
    font-size: 20px;
  }

  .exam-header-layout {
    padding: 12px;
    gap: 12px;
  }

  .exam-stats-right {
    gap: 8px;
    padding: 8px 12px;
  }

  .card-badges {
    gap: 6px;
  }
}

@media (max-width: 1300px) {
  .main-content {
    margin-left: 0;
    padding: 32px 24px;
    max-width: 100vw;
  }

  .sidebar {
    transform: translateX(-100%);
    transition: transform 0.3s;
  }

  .class-grid {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 16px;
  }

  .combined-actions-stats {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }

  .search-box {
    width: 200px;
  }

  .actions-left {
    justify-content: center;
  }

  .inline-stats {
    justify-content: center;
  }

  .pagination-container {
    flex-direction: column;
    gap: 12px;
    align-items: center;
  }

  .pagination-controls {
    flex-wrap: wrap;
    justify-content: center;
  }

  .pagination-settings {
    order: 2;
  }

  .pagination-jumper {
    order: 3;
  }
}

@media (max-width: 768px) {
  .main-content {
    padding: 24px 16px;
  }

  .nav-tabs {
    display: none;
  }

  .user-info {
    display: none;
  }

  .class-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .combined-actions-stats {
    padding: 16px;
    gap: 12px;
  }

  .actions-left {
    flex-direction: column;
    gap: 8px;
    width: 100%;
  }

  .actions-left .btn {
    width: 100%;
    justify-content: center;
  }

  .inline-stats {
    padding: 12px 16px;
    gap: 16px;
  }

  .search-box {
    width: 100%;
  }

  .stat-item {
    flex-direction: row;
    justify-content: space-between;
    width: 100%;
  }

  .modal {
    width: 95%;
    margin: 0 auto;
  }

  .modal-compact {
    width: 95%;
    max-width: 320px;
  }

  .students-grid {
    grid-template-columns: 1fr;
    max-height: 300px;
  }

  .student-card {
    padding: 12px;
    gap: 10px;
  }

  .student-avatar {
    width: 36px;
    height: 36px;
  }

  .student-name {
    font-size: 14px;
    line-height: 20px;
  }

  .student-id {
    font-size: 13px;
  }

  .student-role {
    font-size: 11px;
    padding: 1px 6px;
  }

  .modal-compact .modal-header {
    padding: 10px 12px 0 12px;
    margin-bottom: 10px;
  }

  .modal-compact .modal-form {
    padding: 0 12px;
  }

  .modal-compact .form-group {
    margin-bottom: 10px;
  }

  .form-row-compact {
    flex-direction: column;
    gap: 8px;
  }

  .checkbox-group-compact {
    max-height: 100px;
    padding: 6px 8px;
  }

  .modal-actions-compact {
    padding: 10px 12px;
    margin-top: 10px;
    flex-direction: column;
    gap: 8px;
  }

  .class-actions-buttons {
    gap: 4px;
  }

  .btn-action {
    padding: 5px 6px;
    font-size: 11px;
  }

  .btn-action svg {
    width: 10px;
    height: 10px;
  }

  .btn-compact {
    width: 100%;
    justify-content: center;
  }

  .pagination-container {
    gap: 12px;
  }

  .pagination-controls {
    gap: 4px;
  }

  .pagination-btn {
    padding: 6px 8px;
    font-size: 12px;
  }

  .pagination-jumper {
    gap: 6px;
  }

  .pagination-input {
    width: 50px;
  }
}

@media (max-width: 480px) {
  .main-content {
    margin-top: 73px;
    padding: 20px 12px;
    width: 100vw;
    max-width: 100vw;
  }

  .class-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .class-card {
    padding: 14px;
  }

  .combined-actions-stats {
    padding: 12px;
    gap: 12px;
  }

  .inline-stats {
    flex-direction: column;
    gap: 12px;
    padding: 12px;
  }

  .stat-divider {
    width: 100%;
    height: 1px;
  }

  .page-title {
    font-size: 20px;
    line-height: 28px;
  }

  .pagination-pages {
    gap: 2px;
  }

  .pagination-btn {
    min-width: 36px;
    padding: 6px;
  }

  .pagination-jumper {
    flex-direction: column;
    gap: 8px;
    text-align: center;
  }

  .pagination-container {
    flex-direction: column;
    align-items: center;
    gap: 12px;
  }

  .pagination-info {
    order: 1;
  }

  .pagination-controls {
    order: 2;
  }

  .pagination-settings {
    order: 3;
  }

  .pagination-jumper {
    order: 4;
  }

  .class-actions-buttons {
    gap: 3px;
    margin-top: 12px;
  }

  .btn-action {
    padding: 4px 5px;
    font-size: 10px;
    line-height: 14px;
  }

  .btn-action svg {
    width: 9px;
    height: 9px;
  }

  .btn-compact {
    width: 100%;
    justify-content: center;
  }

  .btn-minimal {
    width: 100%;
    justify-content: center;
  }

  .modal-minimal {
    width: 95%;
    max-width: 280px;
  }

  .modal-large {
    width: 95%;
    max-width: 350px;
  }

  .students-grid {
    grid-template-columns: 1fr;
    max-height: 250px;
    gap: 12px;
  }

  .student-card {
    padding: 10px;
    gap: 8px;
    flex-direction: column;
    text-align: center;
  }

  .student-info {
    text-align: center;
  }

  .students-header {
    text-align: center;
    padding: 12px 0;
  }

  .modal-minimal .modal-header-minimal {
    padding: 6px 10px 0 10px;
    margin-bottom: 6px;
  }

  .modal-minimal .modal-form-minimal {
    padding: 0 10px;
  }

  .modal-minimal .form-group-minimal {
    margin-bottom: 6px;
  }

  .modal-actions-minimal {
    padding: 6px 10px;
    margin-top: 6px;
  }
}
</style>